【发布时间】:2012-09-28 10:49:22
【问题描述】:
我的库中有一个类,我想向用户公开。我不想公开整个类,因为我可能想稍后进行二进制不兼容的更改。我对以下哪种方式最好感到困惑。
案例一:
struct Impl1;
struct Handle1
{
// The definition will not be inline and will be defined in a C file
// Showing here for simplicity
void interface()
{
static_cast<Impl1*>(this)->interface();
}
}
struct Impl1 : public Handle1
{
void interface(){ /* Do ***actual*** work */ }
private:
int _data; // And other private data
};
案例2:
struct Impl2
struct Handle2
{
// Constructor/destructor to manage impl
void interface() // Will not be inline as above.
{
_impl->interface();
}
private:
Impl2* _impl;
}
struct Impl2
{
void interface(){ /* Do ***actual*** work */ }
private:
int _data; // And other private data
};
Handle 类仅用于公开功能。它们将仅在库内创建和管理。继承只是为了抽象实现细节。不会有多个/不同的 impl 类。在性能方面,我认为两者都是相同的。是吗?我正在考虑采用 Case 1 方法。有什么需要注意的问题吗?
【问题讨论】:
-
“我的库中有一个类,我想向用户公开” - 我认为你应该改写:->
-
听起来你是在使用 PIMPL 编译防火墙成语:herbsutter.com/gotw/_101
标签: c++ design-patterns abstraction