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?
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.
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.
To access the object, a weak_ptr can be converted to a shared_ptr using the shared_ptr constructor or the member function lock.
Using weak_ptr and shared_ptr across threads is safe; the weak_ptr/shared_ptr objects themselves aren't thread-safe.
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.
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