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

后端 未结 9 1345
醉梦人生
醉梦人生 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> impl_;
    };
    
    ...
    CopyableFoo (const CopyableFoo& rhs)
        : impl_(new Impl (*rhs.impl_))
    {}
    
    0 讨论(0)
  • 2020-12-23 15:59

    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.

    0 讨论(0)
  • 2020-12-23 16:01

    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.

    0 讨论(0)
提交回复
热议问题