środa, 13 października 2010

The PIMPL Pattern

The PIMPL this is a "private implementation". This pattern is useful to cut a time of compilation.

Advantages:
We don't need attach a lot of headers file to another header file.
We reduce a time of compilation.

Disadvantages:
For each object we must create one dynamic object.

How can we implement it ?

Look at this simple header file :

//Height map header
#include "Camera.h"
#include "Hero.h"
//etc.

class HeightMap{
   private:
   Camera camera;
   Hero hero;
   //etc.
};

We see that we must attach a few headers.
We can create a promising declaration, but we can create by this only a dynamic object.

We can solve this problem by private implementation. There is example of this solution:

//Height map header

class HeightMap_pimpl;

class HeightMap{
private:
   HeightMap_pimpl* pimpl;
};

//cpp file
#include "Camera.h"
#include "Hero.h"

class HeightMap_pimpl{
private:
   Camera camera;
   Hero hero;
}

HeightMap::HeightMap(){ pimpl = new HeightMap_pimpl; }

And that' s it. This is really simple and useful. We can also use a smart pointer from my general library to avoid responsibility to delete an allocated object :

class HeightMap{
private:
   scoped_ptr pimpl;
};

See you  later

1 komentarz: