在C ++中,如果头文件类定义中的任何内容发生更改,则必须重新编译该类的,即使所更改是私有类成员。这是因为C ++的构建模型基于文本包含(textual inclusion),并且因为C ++假定调用者知道一个类的两项内容,而这两项可能会受到私有成员的影响:
PIMPL(Private Implementation 或 Pointer to Implementation),它将类的实现细节从对象表示中移除,放到一个分离的类中,并以一个不公开的指针进行访问:
是C++ 在构建导出库接口时特有的技术手段,优点:
ABI(application binary interface)
**的C++库接口注意ABI并不是API,
通常在C/C++中,API指的就是同应用程序或库一起公开的头文件,它包含各种公开的类型、变量、函数等。
而ABI通常指编译器在构建时应用程序时所需的细节:
一般class
// file widget.h
//
class widget {
// public and protected members
private:
// private members; whenever these change,
// all client code must be recompiled
};
PIMPL 如下:
class widget {
widget();
~widget();
// public and protected members
private:
class impl;
std::unique_ptr<impl> pimpl; // ptr to a forward-declared class
};
class widget::impl{
//private members; fully hidden, can be
//changed at will without recompiling clients
}
widget::widget():pimpl{make_unique<widget::impl>(/*...*/)}
{
}
widget::~widget() = defalut;
避免使用原生指针和显式的delete。要仅使用C ++11最合适的选择是通过unique_ptr来保存Pimpl对象。
每个widget对象都动态分配其impl对象,即不透明的指针pimpl。这样打破了调用者对私有细节的依赖性,包括打破编译时依赖性和二进制依赖性
但这样也会带来性能上 的损失:
所有的private members? 并不是。原因:
difference-between-api-and-abi
Herb Sutter(C++标准委员会成员)一些相关的博客
GotW #7a Solution: Minimizing Compile-Time Dependencies, Part 1
[GotW #7a Solution: Minimizing Compile-Time Dependencies, Part 2
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。