Search code examples
c++c++11moveshared-ptr

Is a moved-from shared_ptr guaranteed to be emptied?


Consider the following code:

struct Bar
{
    std::shared_ptr<int> MemberFunction()
    {
        return std::move(m_memberVariable);
    }

    std::shared_ptr<int> m_memberVariable;
};

Is it guaranteed that the std::move from a shared_ptr<T> will actually remove the reference in the member variable? Or should I copy, clear and return copy to guarantee this*

Clearly in the case of unique_ptr<T> it does the right thing (it cannot possibly not do) but does the standard guarantee that a std::moved from shared_ptr releases its reference? [when it is a member variable, static or global, locals don't matter as they go out of scope]

*possibly "swap and return" is better than "copy, clear and return".


Solution

  • You do indeed have that guarantee. From 20.7.2.2.1/21-22:

    shared_ptr(shared_ptr&& r) noexcept;

    template<class Y> shared_ptr(shared_ptr<Y>&& r) noexcept;

    Effects: Move-constructs a shared_ptr instance from r.

    Postconditions: *this shall contain the old value of r. r shall be empty. r.get() == 0.