为此获得 boost::shared_ptr

Getting a boost::shared_ptr for this(为此获得 boost::shared_ptr)
本文介绍了为此获得 boost::shared_ptr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的代码中广泛使用了 boost:shared_ptr.事实上,在堆上分配的大多数对象都由一个shared_ptr 持有.不幸的是,这意味着我无法将 this 传递给任何采用 shared_ptr 的函数.考虑这个代码:

I am making extensive use of boost:shared_ptr in my code. In fact, most of the objects that are allocated on the heap are held by a shared_ptr. Unfortunately this means that I can't pass this into any function that takes a shared_ptr. Consider this code:

void bar(boost::shared_ptr<Foo> pFoo)
{
    ...
}

void Foo::someFunction()
{
    bar(this);
}

这里有两个问题.首先,这不会编译,因为 shared_ptr 的 T* 构造函数是显式的.其次,如果我强制它使用 bar(boost::shared_ptr<Foo>(this)) 构建,我将创建第二个指向我的对象的共享指针,最终将导致双重删除.

There are two problems here. First, this won't compile because the T* constructor for shared_ptr is explicit. Second, if I force it to build with bar(boost::shared_ptr<Foo>(this)) I will have created a second shared pointer to my object that will eventually lead to a double-delete.

这让我想到了我的问题:是否有任何标准模式可以从这些对象之一的方法内部获取您知道存在的现有共享指针的副本?在这里使用侵入式引用计数是我唯一的选择吗?

This brings me to my question: Is there any standard pattern for getting a copy of the existing shared pointer you know exists from inside a method on one of those objects? Is using intrusive reference counting my only option here?

推荐答案

您可以从 enable_shared_from_this 然后您可以使用shared_from_this()"而不是this"来生成指向您自己的 self 对象的共享指针.

You can derive from enable_shared_from_this and then you can use "shared_from_this()" instead of "this" to spawn a shared pointer to your own self object.

链接中的示例:

#include <boost/enable_shared_from_this.hpp>

class Y: public boost::enable_shared_from_this<Y>
{
public:

    shared_ptr<Y> f()
    {
        return shared_from_this();
    }
}

int main()
{
    shared_ptr<Y> p(new Y);
    shared_ptr<Y> q = p->f();
    assert(p == q);
    assert(!(p < q || q < p)); // p and q must share ownership
}

当从成员函数生成线程到 boost::bind 到 shared_from_this() 而不是 this 时,这是一个好主意.它将确保对象不被释放.

It's a good idea when spawning threads from a member function to boost::bind to a shared_from_this() instead of this. It will ensure that the object is not released.

这篇关于为此获得 boost::shared_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)