Pimpl

From Schmid.wiki
Jump to: navigation, search

PIMPL Components

C++

Header file thing.hpp:

#include <boost/scoped_ptr.hpp>

class Reusable_component; // forward declaration

class Thing { // public interface
public:

    Thing();
    ~Thing();
    int do_stuff();

private:

    // Two different kinds of PIMPL components:
    // - A component defined externally, reusable by other classes:
    boost::scoped_ptr< Reusable_component > stuff_;

    // - A component defined internally:
    class Internal_component;
    boost::scoped_ptr< Internal_component > doing_;
};

header file reusable_component.hpp:

struct Reusable_component {
    int result() { return 7; }
};

implementation file thing.cpp:

struct Thing::Internal_component {
    int do_that( int x ) { return x * 2; }
};

Thing::Thing()
: stuff_( new Reusable_component ),
  doing_( new Internal_component )
{}

int Thing::do_stuff() {
    // use PIMPL components in implementation file
    doing_->do_that( stuff_->result() );
}

// Dtor needs to be defined here and not in the header file, as
// this also defines the scoped_ptr dtor implementation, which needs
// to know the size of Internal_component, which is not defined in
// the header file. scoped_ptr uses the checked_delete idiom to
// ensure that the size of Internal_component is known when the
// dtor is defined.
Thing::~Thing() {}
Personal tools