是否有boost :: weak_intrusive_pointer? [英] Is there a boost::weak_intrusive_pointer?
问题描述
出于遗留原因,我需要使用介入式指针,因为我需要能够将原始指针转换为智能指针.
For legacy reasons I need to use intrusive pointers, as I need the ability to convert raw pointers to smart pointers.
但是,我发现没有弱的侵入性指针可以增强.我确实在boost线程列表中找到了关于它的话题,但是没有什么具体的.
However I noticed there is no weak intrusive pointer for boost. I did find a talk about it on the boost thread list, however nothing concrete.
有人知道弱侵入指针的线程安全实现吗?
Does anyone know of a thread safe implementation of weak intrusive pointer?
谢谢 丰富
推荐答案
这没有任何意义.
要详细说明:weak_ptr
指向与shared_ptr
相同的counter
对象实例.当shared_ptr
超出范围时,counter
的实例将停留(有效计数为0),这允许weak_ptr
实例检查其是否有效指向了释放的对象.
To elaborate: weak_ptr
points to the same instance of a counter
object that shared_ptr
do. When the shared_ptr
goes out of scope, the instance of the counter
stays (with a count effectively at 0), which allows the weak_ptr
instances to check that they effectively point to a freed object.
使用介入式计数,计数器被集成在对象中.当计数达到0时,对象通常被回收或删除...但是关键是计数器不再可用.这样做的理由是,这样可以实现更高效的存储(一个单块)和更快的速度(缓存局部性).
With Intrusive Counting, the counter is integrated within the object. When the count reaches 0, the object is usually either recycled or deleted... but the point is the counter is no longer available. The rationale is that this allow for a more efficient storage (1 single chunk) and greater speed (cache locality).
如果您需要弱引用计数并且不关心侵入式计数的好处,则可以组合使用shared_ptr
和weak_ptr
.
If you need Weak Reference counting and do not care for the benefits of intrusive counting, you can use a combination of shared_ptr
and weak_ptr
.
想法是将计数器与对象解除关联.
The idea is to deassociate the counter from the objects.
class Counted
{
// bla
private:
boost::shared_ptr<int> mCounter;
};
现在您可以返回弱句柄了:
Now you can return weak handles:
class WeakHandle
{
public:
explicit WeakHandle(Counted& c): mCounter(c.mCounter), mObject(&c) {}
bool expired() const { return mCounter.expired(); }
private:
boost::weak_ptr<int> mCounter;
Counted* mObject;
};
在这里,我们将计数器的寿命与对象的寿命解除关联,以便它可以在对象的破坏中幸免于难…….这样就可以有效地实现weak_ptr
.
Here, we deassociate the lifetime of the counter from the lifetime of the object, so that it will survive the destruction of the object... partially. Thus making the weak_ptr
effectively possible.
当然,使用shared_ptr
和weak_ptr
这是线程安全的;)
And of course, using shared_ptr
and weak_ptr
this is Thread Safe ;)
这篇关于是否有boost :: weak_intrusive_pointer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!