PIMPL

2011-05-04 56 views
0

的更简单的形式为什么不选择这样的设计: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){} 
}; 

我可以隐藏实现细节,并与变量加速编译和定义静态函数源文件?如果没有,这个设计有什么问题(除了继承)?

回答

6

如果您使用全局向量来存储您建议的状态,您将不得不确保类A的不同实例使用向量的不同部分(除了这样做的明显困难之外,请考虑这样做会变得多么困难如果不同的线程使用A)的不同实例。如果A是一个单身人士,这种设计只会非常有意义。

10

在第一种情况下,整个程序只有一个impl_database_for_do_something实例。你需要每个A实例的一个实例。所以这个代码在任何意义上都是不相同的。

2

您的第一个设计有一个向量为全部A的实例;后者每实例有一个。阅读实例变量与类变量。

0

这完全不是PIMPL:指向IMPLementation的指针。

你可以这样来做:

// 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); 
} 

警告:这个代码不具有适当的复制/分配行为的处理,它作为练习留给读者。