以下实现pImpl习语的缺点是什么?pImpl idiom - 将私有类实现放入cpp中的缺点是什么?
// widget.hpp
// Private implementation forward declaration
class WidgetPrivate;
// Public Interface
class Widget
{
private:
WidgetPrivate* mPrivate;
public:
Widget();
~Widget();
void SetWidth(int width);
};
// widget.cpp
#include <some_library.hpp>
// Private Implementation
class WidgetPrivate
{
private:
friend class Widget;
SomeInternalType mInternalType;
SetWidth(int width)
{
// Do something with some_library functions
}
};
// Public Interface Implementation
Widget::Widget()
{
mPrivate = new WidgetPrivate();
}
Widget::~Widget()
{
delete mPrivate;
}
void Widget::SetWidth(int width)
{
mPrivate->SetWidth(width);
}
我不希望有单独的头和源类的私有实现部分是因为该代码是相同的类基本上 - 他们不应住在一起呢?
这个版本的其他选择会更好吗?
啊这是一个有趣的想法。我想我可以总结你的替代大包括“包括非pimpl'ed头只在你的.cpp的”。是对的吗? – UberMongoose
@UberMongoose这就是它。最主要的是外部依赖不应该出现在你的库的用户将使用的任何头文件中。下面的细节实际上就是最适合你的东西。 –