14

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

Mike Vine
  • 9,468
  • 25
  • 44
  • Do you want in practice, or do you want chapter-and-verse from the standard? In practice, even if the standard missed insisting on this, any compiler which did it would be considered evil. – Yakk - Adam Nevraumont Jun 17 '13 at 13:15

1 Answers1

17

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.

Community
  • 1
  • 1
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084