Why should the quot;PIMPLquot; idiom be used?(为什么要“PIMPL习惯用法?)
问题描述
背景:
PIMPL Idiom(指向实现的指针)是一种实现隐藏的技术,其中公共类包装了在公共类所属的库之外无法看到的结构或类.
The PIMPL Idiom (Pointer to IMPLementation) is a technique for implementation hiding in which a public class wraps a structure or class that cannot be seen outside the library the public class is part of.
这对库的用户隐藏了内部实现细节和数据.
This hides internal implementation details and data from the user of the library.
在实现这个习惯用法时,为什么要将公共方法放在 pimpl 类而不是公共类上,因为公共类方法的实现会被编译到库中,而用户只有头文件?
When implementing this idiom why would you place the public methods on the pimpl class and not the public class since the public classes method implementations would be compiled into the library and the user only has the header file?
为了举例说明,这段代码将 Purr()
实现放在 impl 类上并对其进行了包装.
To illustrate, this code puts the Purr()
implementation on the impl class and wraps it as well.
为什么不直接在公共类上实现 Purr?
// header file:
class Cat {
private:
class CatImpl; // Not defined here
CatImpl *cat_; // Handle
public:
Cat(); // Constructor
~Cat(); // Destructor
// Other operations...
Purr();
};
// CPP file:
#include "cat.h"
class Cat::CatImpl {
Purr();
... // The actual implementation can be anything
};
Cat::Cat() {
cat_ = new CatImpl;
}
Cat::~Cat() {
delete cat_;
}
Cat::Purr(){ cat_->Purr(); }
CatImpl::Purr(){
printf("purrrrrr");
}
推荐答案
- 因为您希望
Purr()
能够使用CatImpl
的私有成员.如果没有friend
声明,Cat::Purr()
将不允许这样的访问. - 因为你不会混合职责:一类实现,一类转发.
- Because you want
Purr()
to be able to use private members ofCatImpl
.Cat::Purr()
would not be allowed such an access without afriend
declaration. - Because you then don't mix responsibilities: one class implements, one class forwards.
这篇关于为什么要“PIMPL"习惯用法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么要“PIMPL"习惯用法?
- XML Schema 到 C++ 类 2022-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- DoEvents 等效于 C++? 2021-01-01
- GDB 不显示函数名 2022-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- 将 hdc 内容复制到位图 2022-09-04
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- 如何提取 __VA_ARGS__? 2022-01-01
- 将函数的返回值分配给引用 C++? 2022-01-01