How to convert boost :: weak_ptr to boost :: shared_ptr

I have shared_ptr and weak_ptr

typedef boost::weak_ptr<classname> classnamePtr;
typedef boost::shared_ptr<x> xPtr;

how to convert weak_ptr to shared_ptr

shared_ptr = weak_ptr;
Xptr = classnameptr; ?????
+3
source share
3 answers

As already mentioned,

boost::shared_ptr<Type> ptr = weak_ptr.lock(); 

If you do not want an exception or just use the cast constructor

boost::shared_ptr<Type> ptr(weak_ptr);

This will happen if the weak pointer is already deleted.

+8
source

You do not convert weak_ptrto shared_ptr, as this may lead to the full purpose of use weak_ptr.

To get shared_ptrfrom instance a weak_ptr, call lockon weak_ptr.
Usually you do the following:

weak_ptr<foo> wp = ...;

if (shared_ptr<foo> sp = wp.lock())
{
    // safe to use sp
}
+7
source
boost::shared_ptr<Type> ptr = weak_ptr.lock(); // weak_ptr being boost::weak_ptr<Type>
+2
source

Source: https://habr.com/ru/post/1768406/


All Articles