粉刺的一种简单形式
A simpler form of pimpl
为什么不选择这个设计:
// A.hpp
class A
{
public:
void do_something();
};
// A.cpp
#include "A.hpp"
#include <vector>
std::vector<int> impl_database_for_do_something;
static void impl_helper_for_do_something(const std::vector<int>& database){}
void A::do_something(){ impl_helper_for_do_something(impl_database_for_do_something); }
代替这个:
// A.hpp
#include <vector>
class A
{
public:
void do_something();
private:
std::vector<int> database_for_do_something_;
void helper_for_do_something(const std::vector<int>& database){}
};
我可以隐藏实现细节和加速编译与变量和静态函数定义在源文件?如果不是,这个设计有什么问题(除了继承)?
在第一种情况下,整个程序只有一个impl_database_for_do_something实例。你希望每个a的实例对应一个它的实例,所以代码在任何意义上都不是等价的。
如果你按照你的建议使用全局向量来存储状态,你将不得不以某种方式确保类A的不同实例使用向量的不同部分(除了这样做的明显困难之外,考虑到如果不同的线程使用A的不同实例,这会变得多么困难)。这种设计只有在A是单例时才有意义。
您的第一个设计有一个向量所有 A
实例;后者每个实例有一个。
这根本不是PIMPL:指向实现的指针。
你可以这样做:
// A.hpp
#include <boost/shared_ptr.hpp>
class A
{
public:
A();
void foo();
private:
struct Impl;
boost::shared_ptr<Impl> _impl;
};
// A.cpp
#include <vector>
#include "A.hpp"
struct A::Impl {
std::vector<int> _data;
};
A::A(): _impl(new std::vector<int>()) {}
void A::foo() {
_impl->_data.push_back(3);
}
警告:此代码没有处理正确的复制/赋值行为,留给读者作为练习。
相关文章:
- 有没有一种简单的方法可以从 c++ 中的路径获取文件名?
- 有没有一种简单的方法可以在对象向量上调用构造函数?
- 有没有一种简单的方法来调用带有默认参数的函数?
- 有没有一种简单的方法来检查C++中的不安全表达式
- 有没有一种简单的方法可以在C++中获取特定索引之后向量中的所有项目?
- 有没有一种简单的方法可以将矢量 int 集转换为字符串输出?
- C++11 中的随机数:有没有一种简单的方法可以将生成器种子放在代码的一个位置,然后在不同的函数中使用它?
- 是否有一种简单的方法可以从普通的 win32 C++代码向应用程序见解提供数据?
- 有没有一种简单的方法可以从嵌入的 GNU ARM C++字符串中解析浮点数?
- 有没有一种简单的方法可以忽略 c++ 中的索引错误
- 有没有一种简单的方法来计算库中记录的函数
- 有没有一种简单的方法可以将系统命令的输出转换为字符串
- 有没有一种简单的方法可以使用SFML在后台线程中播放声音
- 是否有一种简单的方法可以在运行时在C 中创建/名称对象
- 是否有一种简单的方法来找出Boost :: Adjacency_list是否为空
- 需要一种简单的方法来用C CLI嵌入Ironpython
- 有没有一种简单的方法可以将库文件包含在MSVC中
- 有没有一种简单的方法来关闭多个手柄
- 布尔运算符,在C++中有没有一种简单的方法可以做到这一点
- 有没有一种简单的方法可以将多个资源添加到 Win32/C++ 项目