pimpl idiom 是一种新式 C++ 技术,用于隐藏实现、最小化耦合和分离接口。 Pimpl 是“指向实现的指针”的缩写。你可能已经熟悉这个概念,但知道它的其他名称,如柴郡猫或编译器防火墙成语。
为何使用 pimpl?
下面是 pimpl idiom 如何改善软件开发生命周期:
编译依赖项的最小化。
接口和实现的分离。
可移植性。
Pimpl 标头
// my_class.h
class my_class {
// ... all public and protected stuff goes here ...
private:
class impl; unique_ptr<impl> pimpl; // opaque type here
};
pimpl idiom 避免重新生成级联和脆对象布局。 它非常适合(可传递)常用类型。
Pimpl 实现
在 .cpp 文件中定义 impl 类。
// my_class.cpp
class my_class::impl { // defined privately here
// ... all private data and functions: all of these
// can now change without recompiling callers ...
};
my_class::my_class(): pimpl( new impl )
{
// ... set impl values ...
}
最佳实践
请考虑是否添加对非引发交换专用化的支持。