开发者

how to convert a boost::weak_ptr to a boost::shared_ptr

i have a shared_ptr and a weak_ptr

typedef boost::weak_ptr<classname> classnamePtr;
typedef boost::shared_ptr<x> xPtr;
开发者_开发问答

how to convert a weak_ptr to a shared_ptr

shared_ptr = weak_ptr;
Xptr = classnameptr; ?????


As already said

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

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

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

This will throw if the weak pointer is already deleted.


You don't convert a weak_ptr to a shared_ptr as that would defeat the whole purpose of using weak_ptr in the first place.

To obtain a shared_ptr from an instance of a weak_ptr, call lock on the weak_ptr.
Usually you would do the following:

weak_ptr<foo> wp = ...;

if (shared_ptr<foo> sp = wp.lock())
{
    // safe to use sp
}


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜