C++ Boost



PIMPL is a C++ programming idiom described by Herb Sutter [10] which stands for "Private Implementation". It is also referred to as the "Handle Body Idiom". Included in this library is a program called demo_pimpl.cpp which illustrates how this is used. The file demo_pimpl_A.hpp contains the declaration of the a class that hides its implementation by including a pointer to struct B that is only defined as a pointer.

// class whose declaration is hidden by a pointer
struct B;

struct A {
    // class a contains a pointer to a "hidden" declaration
    B *pimpl;
    template<class Archive>
    void serialize(Archive & ar, const unsigned int file_version);
Serialization of A requires access to the definition of B in order so it is defined in the separately compiled module: demo_pimpl_A.cpp by:

#include "demo_pimpl_A.hpp"

// "hidden" definition of class B
struct B {
    int b;
    template<class Archive>
    void serialize(Archive & ar, const unsigned int file_version){
        ar & b;

A::A() :
    pimpl(new B)

    delete pimpl;

// now we can define the serialization for class A
template<class Archive>
void A::serialize(Archive & ar, const unsigned int file_version){
    ar & pimpl;
As described in [10] this brings the following advantages: So, we compile the modules and everything is fine. However when we link, we get an error. Two symbols are undefined:

void A::serialize(boost::archive::text_oarchive & ar, const unsigned int file_version);
void A::serialize(boost::archive::text_iarchive & ar, const unsigned int file_version);
The problem is that when compiling the above code, there is no instantiation of the serialize template. There can't be as its not "known" what types of archives the serialization is going to be used with. So these functions are "missing" when an attempt to link is made. The solution is to explicitly instantiate serialization code for those archives which are going to be used. In this example, including the the following code in any *.cpp file does just that:

#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>

template void A::serialize<boost::archive::text_iarchive>(
    boost::archive::text_iarchive & ar, 
    const unsigned int file_version
template void A::serialize<boost::archive::text_oarchive>(
    boost::archive::text_oarchive & ar, 
    const unsigned int file_version
The program should now link as well as compile.

The downside of this is that one has to know which archives are going to be used with hidden serializations. This is an effect of using template driven code. One can invoke explicity instantiation for all known templates and presume that the linker will exclude unreferenced code. This should work but is platform dependent.

© Copyright Robert Ramey 2002-2004. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)