SatView: Pointer Perfect, part 3.5 - SMART PIMPL
(Page 3 of 4 )
Pimpls are effective when you want to hide the private implementation of a class from its users and only publish its public interface (see my article about Pimpls). The characteristics of pointers lay at the basis of a pimpled implementation and we have seen that when we use built-in pointers, there are many ways to (accidentally) create memory-leaks. This looks like a great opportunity to use smart pointers, but we will see that our choice must be narrowed down to the usage of the boost::shared_ptr if we are to implement a class with its private implementation completely hidden in the source file. The reason for this is that the boost::shared_ptr is the only smart pointer allowing for incomplete types to be assigned to it.
But what better way to find out than by code examples? Let's try to implement the pimpl using all three types of smart pointers. The following classes don’t do anything, except demonstrate the usage of smart pointers when implementing pimpls.
// file: pimpl_auto.h
#ifndef __PIMPL_AUTO_H
#define __PIMPL_AUTO_H
class AutoImpl; // forward declaration
class PimplAuto {
private:
std::auto_ptr<AutoImpl> m_pImpl;
};
#endif
// eof
// file: pimpl_scoped.h
#ifndef __PIMPL_SCOPED_H
#define __PIMPL_SCOPED_H
class ScopedImpl; // forward declaration
class PimplScoped {
private:
boost::scoped_ptr<ScopedImpl> m_pImpl;
};
#endif
// eof
// file: pimpl_shared.h
#ifndef __PIMPL_SHARED_H
#define __PIMPL_SHARED_H
class SharedImpl; // forward declaration.
class PimplShared {
private:
boost::shared_ptr<SharedImpl> m_pImpl;
};
#endif
// eof
Don’t be fooled in thinking that all these classes work after you included them, because the compiler will only start complaining when you try to instantiate them.
#include <memory>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include “pimpl_auto.h”
#include “pimpl_scoped.h”
#include “pimpl_shared.h”
int main(int argc, char *argv[])
{
PimplAuto test1;
PimplScoped test2;
PimplShared test3;
return 0;
}
In the case of test1 (using the std::auto_ptr), the compiler cannot work out what the destructor for the private implementation looks like, which is fair since we have only forward declared it. The solution would be to separate the interface of the private implementation into a separate header file, so that we can include it in the header file of the public interface. This is quite common when implementing the Bridge pattern, but I prefer not to expose the private interface in any way when implementing a pimpl.
The same happens with test2 (using the boost::scoped_ptr). The compiler needs to determine how to destroy the private implementation, but fails since the type is incomplete. The only smart pointer that can deal with the incomplete type at this point turns out to be the boost::shared_ptr, which compiles (and runs) fine.
Next: BOOST::WEAK_PTR >>
More C# Articles
More By J. Nakamura