# PIMPL 模式的实现及应用。

PIMPL 也可以称为一种设计模式了。

pimpl 手法在 C++ 里已是“高手”们广泛运用的成熟方法之一，它的优点很多，诸如降低编译依赖、提高重编译速度之类的工具性优势自不待赘言，而其对“保持接口稳定性”的优点更值得称道。

It makes it possible to avoid other classes to know internal data structures and other information of the class. It also simplifies some #includepreprocessor instructions.避免别的class知道其内部的数据结构。还可以简化预编译指令。

File foo.h

class CFoo
{
public:
CFoo();
~CFoo();
bool ProcessFile(const CString & csFile);
private:
CFooInternalData    m_data;
}

File foo.cpp

#include "FooInternalData.h"

#include "foo.h"

CFoo::CFoo()
{
}

CFoo::~CFoo()
{
}

bool CFoo::ProcessFile(const CString & csFile)
{
//do something
return true;
}

Main File

#include "FooInternalData.h"

#include "foo.h"

int main()
{
CFoo foo;
foo.ProcessFile("c:\\data.bin");
return 0;
}


The problem with this simple way of coding is that in your main file, you must include the foo.h to use it, but at the same time you must also include all needed files to allow the compiler to work correctly. In fact, the main does not need to include FooInternalData.h and Header.h (which are CFoo internal structures) except for compilation.... So with very big classes, you might do some huge includes and in this case, you can have some compiler or linker errors because files are already included elsewhere.

pimpl 手法能比较完善的解决这些问题。利用 pimpl 手法，我们把数据细节隐藏到一个实现类里：CFoo_pimpl，而 CFoo 的 private 部分只剩下一个指针，那就是传说中滴 pimpl 指针

## The Same Example with PIMPL

File foo.h

//here just declare the class PIMPL to compile.
//As I use this class with a pointer, I can use this declaration
class CFoo_pimpl;

class CFoo
{
public:
CFoo();
~CFoo();
bool ProcessFile(const CString & csFile);
private:
std::auto_ptr<CFoo_pimpl>    m_pImpl;
}

File foo.cpp

#include "FooInternalData.h"

#include "foo.h"

//here defines PIMPl class, because it is use only in this file
class CFoo_pimpl()
{
public:
CFoo_pimpl()
{
}

~CFoo_pimpl()
{
}
bool ProcessFile(const CString & csFile)
{
//do something
return true;
}
};

CFoo::CFoo()
:m_pImpl(new CFoo_pimpl())
{
}

CFoo::~CFoo()
{
//do not have to delete, std::auto_ptr is very nice
}

bool CFoo::ProcessFile(const CString & csFile)
{
//just call your PIMPL function ;-)
return m_pImpl->ProcessFile(csFile);
}

Main File

#include "foo.h"

int main()
{
CFoo foo;
foo.ProcessFile("c:\\data.bin");
return 0;
}


The result is obvious: simplicity of use!! The main does not need more includes for internal structures of CFoo class.

Thus it is an excellent optimization to minimize linker and compiler errors.

## Conclusion

It is a very simple and nice way for good coding!!! If you want to use classes in other projects, it does not introduce including difficulties.

Unfortunately, you must add some more code to type.

posted @ 2011-11-23 19:05  kanego  阅读(11684)  评论(5编辑  收藏  举报