Search code examples
c++memoryshared-ptr

C++ std::shared_ptr, is operator= overloaded to use copy constructor?


If I do the following:

class Foo
{
    std::shared_ptr<Bar> bar;
    Foo(std::shared_ptr<Bar> bar)
    {
        this->bar = bar;
    }
}
std::shared_ptr<Foo> func()
{
    std::shared_ptr<Bar> bar_ptr(new Bar());
    std::shared_ptr<Foo> foo_ptr(new Foo(bar_ptr));
    return foo_ptr;
}

Will foo_ptr in func() have a valid pointer in its member variable bar? It seems that it only would if when setting this->bar = bar that the constructor parameter gets copied. Is the = operator for std::shared_ptr overridden to call the copy constructor always?


Solution

  • Both the copy constructor and the assignment operator will make the receiver share ownership with the one you pass in. However they perform that internally internally is an implementation detail.

    Of course, if this->bar was managing something, then it would release its shared ownership of it (and if it is the last one owning it, whatever Bar was there will get deleted).

    But my concern here is that both this-> bar and bar in the constructor of Foo are the same reference meaning that there is really only one shared_ptr object in memory, but I have 2 variables referencing that shared_ptr.

    They are not references, bar and this->bar are two different std::shared_ptr objects that, after the assignment, will point (internally) to the same place in memory (but they are still two different objects). However, std::shared_ptr is a class that knows how many other std::shared_ptrs are pointing to it (shared ownership) and will properly delete the object only once all of the others are gone (so only the last std::shared_ptr will destroy it).