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"习惯用法?


基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01