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".
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_ptrinstance fromr.Postconditions:
*thisshall contain the old value ofr.rshall be empty.r.get() == 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With