Search code examples
c++c++11shared-ptrcopy-constructor

Does std::shared_ptr<X> have a copy constructor?


I am learning std::shared_ptr.
I read a document about constructors of shared_ptr to find its copy constructor.

I could find a constructor,

shared_ptr( const shared_ptr& r );

but it seems it is not a simple copy constructor I expected,

shared_ptr( shared_ptr& r );

and it seems it does not shares reference counter.

Why shared_ptr does not have a simple copy constructor?

In case, I write what I really want to do below,

class A {
public:
    A(shared_ptr<X>& sptr) : sptr_(sptr) {}
private:
    shared_ptr<X> sptr_;
};

Solution

  • Why shared_ptr does not have a simple copy constructor?

    The standard says that:

    A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, [...]

    There is nothing such a simple copy constructor. std::shared_ptr has a perfectly valid copy constructor instead. It constructs a std::shared_­ptr object that shares ownership with the given one (if valid).