When using the pImpl idiom is it preferable to use a boost:shared_ptr
instead of a std::auto_ptr
? I\'m sure I once read that the boost version is
If you want a copyable class, use scoped_ptr
, which forbids copying, thus making your class hard to use wrong by default (compared to using shared_ptr
, the compiler won't emit copy facilities on its own; and in case of shared_ptr
, if you don't know what you do [which is often enough the case even for wizards], there would be strange behaviour when suddenly a copy of something also modifies that something), and then out-define a copy-constructor and copy-assignment:
class CopyableFoo {
public:
...
CopyableFoo (const CopyableFoo&);
CopyableFoo& operator= (const CopyableFoo&);
private:
scoped_ptr<Impl> impl_;
};
...
CopyableFoo (const CopyableFoo& rhs)
: impl_(new Impl (*rhs.impl_))
{}
boost::shared_ptr is specially tailored to work for pimpl idiom. One of the main advantages is that it allows not to define the destructor for the class holding pimpl. Shared ownership policy maybe both advantage and disadvantage. But in later case you can define copy constructor properly.
Don't try so hard to shoot yourself in the foot, in C++ you have plenty of opportunities :) There is no real need to use either auto pointers, since you perfectly know when your object should go in and out of life (in your constructor(s) and destructor).
Keep it simple.