Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static_pointer_cast for weak_ptr

Tags:

c++11

weak-ptr

In c++0x, there is a std::static_pointer_cast for std::shared_ptr, but there is no equivalent method for std::weak_ptr. Is this intentional, or an oversight? If an oversight, how would I define an appropriate function?

like image 290
tgoodhart Avatar asked May 19 '11 23:05

tgoodhart


People also ask

Can a Weak_ptr point to a Unique_ptr?

You can implement weak_ptr which works correctly with unique_ptr but only on the same thread - lock method will be unnecessary in this case.

What is Static_pointer_cast?

std::static_pointer_castReturns a copy of sp of the proper type with its stored pointer casted statically from U* to T*. If sp is not empty, the returned object shares ownership over sp's resources, increasing by one the use count. If sp is empty, the returned object is an empty shared_ptr.

How can a Weak_ptr be turned into a shared_ptr?

To access the object, a weak_ptr can be converted to a shared_ptr using the shared_ptr constructor or the member function lock.

Is Weak_ptr lock thread safe?

Using weak_ptr and shared_ptr across threads is safe; the weak_ptr/shared_ptr objects themselves aren't thread-safe.


1 Answers

This ought to do it for you:

template<class T, class U>
std::weak_ptr<T>
static_pointer_cast(std::weak_ptr<U> const& r)
{
    return std::static_pointer_cast<T>(std::shared_ptr<U>(r));
}

This will throw an exception if the weak_ptr has expired. If you would rather get a null weak_ptr, then use r.lock() instead.

like image 67
Howard Hinnant Avatar answered Oct 13 '22 19:10

Howard Hinnant