shared_ptr<int> p(new int(5));
weak_ptr<int> q(p);
// some time later
if(shared_ptr<int> r = q.lock())
{
// use *r
}
Boost - the weak_ptr has some nice features that make it safe to use, if you are also using shared_ptr. You keep a weak_ptr reference to an instance that is managed by shared_ptr lifetime. When you need to use the underlying instance, convert it to a shared_ptr instance using the constructor of the shared_ptr class, or the lock method. The operation will fail if the underlying instance was deleted. The use is thread safe in the same fashion as the shared_ptr class:
shared_ptr<int> p(new int(5));
weak_ptr<int> q(p);
// some time later
if(shared_ptr<int> r = q.lock())
{
// use *r
}
发布评论
评论(2)
Boost -
weak_ptr
如果您也使用shared_ptr
,那么它有一些很好的功能,可以安全使用。 您保留对由shared_ptr
生命周期管理的实例的weak_ptr
引用。 当您需要使用底层实例时,请使用shared_ptr
类的构造函数或lock
方法将其转换为shared_ptr
实例。 如果底层实例被删除,操作将会失败。 使用与shared_ptr
类相同的方式是线程安全的:Boost - the
weak_ptr
has some nice features that make it safe to use, if you are also usingshared_ptr
. You keep aweak_ptr
reference to an instance that is managed byshared_ptr
lifetime. When you need to use the underlying instance, convert it to ashared_ptr
instance using the constructor of theshared_ptr
class, or thelock
method. The operation will fail if the underlying instance was deleted. The use is thread safe in the same fashion as theshared_ptr
class:“boost::weak_ptr”与“boost::shared_ptr”配合得非常好(tr1 中也可用)
"boost::weak_ptr" works really well with "boost::shared_ptr" (also available in tr1)