Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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".

like image 509
Mike Vine Avatar asked Jun 17 '13 13:06

Mike Vine


1 Answers

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.

like image 192
Kerrek SB Avatar answered Sep 24 '22 10:09

Kerrek SB