【问题标题】:Hide contents of third-party C++ header file隐藏第三方 C++ 头文件的内容
【发布时间】:2012-12-16 16:36:21
【问题描述】:

我正在用 C++ 创建一个静态库来定义一个其他人可以在他们的代码中使用的类。但是,该类的成员是从别人那里获得的头文件中定义的类型,我不想分发这个人的头文件的内容。

这是当前的公共接口(interface.h):

class B {
    TypeToHide t;
    // other stuff ...  
};

class A {
    double foo();
    B b;
};

下面是编译成静态库(code.cpp)的代码:

double A::foo() {
    // ...
}

这是我需要隐藏其内容的文件(HideMe.h):

struct TypeToHide {
    // stuff to hide
};

如何隐藏 HideMe.h 的内容?理想情况下,我可以将 HideMe.h 中的整个结构粘贴到 code.cpp 中。

【问题讨论】:

    标签: c++ hide static-libraries header-files


    【解决方案1】:

    您可以使用 PIMPL 成语(Chesshire Cat,Opaque Pointer,随便你怎么称呼它)。

    由于现在的代码,您无法隐藏TypeToHide 的定义。另一种选择是:

    //publicHeader.h
    class BImpl;          //forward declaration of BImpl - definition not required
    class B {
        BImpl* pImpl;     //ergo the name
        //wrappers for BImpl methods
    };
    
    //privateHeader.h
    class BImpl
    {
        TypeToHide t;  //safe here, header is private
        //all your actual logic is here
    };
    

    【讨论】:

    • 好的,所以使用 PIMPL 习语或多或少是处理此类情况的标准方法?
    【解决方案2】:

    比 Pimpl 更简单,您可以使用指向 TypeToHideforward declaration 的指针:

    class B {
        TypeToHide* t;
        // other stuff ...  
    };
    

    只要您不需要了解用户代码的 t 内部结构,您就不必公开它,它会在您的库中保持安全。
    库中的代码必须知道TypeToHide 是什么,但这不是问题。

    【讨论】:

    • 谢谢。 PIMPL 和你的建议有什么区别? (我是 PIMPL 成语的新手,请原谅我的无知。)
    • Pimpl 是一种更加结构化的范例,它声称您通常应该避免暴露您的类型的内部结构。相反,您应该声明一个指向实际实现的指针(P->impl)并且只公开这个指针。对我来说,有时这个原则过于激进,我很乐意公开一些实现。例如,在这个问题中,您可能只想隐藏 TypeToHide 的实现细节,尽管根据 Pimpl 您应该将 B 本身隐藏在 Bimpl 类型后面(Luchian 很好地证明了这一点)。
    • 我明白了。这就说得通了。感谢您的教育:)
    猜你喜欢
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多