std::auto_ptr or boost::shared_ptr for pImpl idiom?

后端 未结 9 1382
醉梦人生
醉梦人生 2020-12-23 15:04

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

9条回答
  •  情话喂你
    2020-12-23 15:57

    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_;
    };
    
    ...
    CopyableFoo (const CopyableFoo& rhs)
        : impl_(new Impl (*rhs.impl_))
    {}
    

提交回复
热议问题