C++ 为此获得 boost::shared_ptr

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/142391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:10:43  来源:igfitidea点击:

Getting a boost::shared_ptr for this

c++boost

提问by Joe Ludwig

I am making extensive use of boost:shared_ptrin 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 thisinto any function that takes a shared_ptr. Consider this code:

boost:shared_ptr在我的代码中广泛使用。实际上,在堆上分配的大多数对象都由shared_ptr. 不幸的是,这意味着我无法传入this任何需要shared_ptr. 考虑这个代码:

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

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

There are two problems here. First, this won't compile because the T* constructor for shared_ptris 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.

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

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?

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

回答by Brian R. Bondy

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

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

Example in the link:

链接中的示例:

#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
}

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::bind 到 shared_from_this() 而不是 this 时,这是一个好主意。它将确保对象不被释放。

回答by Mark Ransom

Just use a raw pointer for your function parameter instead of the shared_ptr. The purpose of a smart pointer is to control the lifetime of the object, but the object lifetime is already guaranteed by C++ scoping rules: it will exist for at least as long as the end of your function. That is, the calling code can't possibly delete the object before your function returns; thus the safety of a "dumb" pointer is guaranteed, as long as you don't try to delete the object inside your function.

只需为您的函数参数使用原始指针而不是 shared_ptr。智能指针的目的是控制对象的生命周期,但是 C++ 范围规则已经保证了对象的生命周期:它至少会存在到函数结束时。也就是说,调用代码不可能在函数返回之前删除对象;因此,只要您不尝试删除函数内的对象,就可以保证“哑”指针的安全性。

The only time you need to pass a shared_ptr into a function is when you want to pass ownership of the object to the function, or want the function to make a copy of the pointer.

唯一需要将 shared_ptr 传递给函数的时间是当您想将对象的所有权传递给函数,或者希望函数制作指针的副本时。

回答by David Pierre

boost has a solution for this use case, check enable_shared_from_this

boost 有针对此用例的解决方案,请检查enable_shared_from_this

回答by Greg Rogers

Are you really making more shared copies of pFoo inside bar? If you aren't doing anything crazy inside, just do this:

你真的在 bar 内制作更多的 pFoo 共享副本吗?如果你没有在内心做任何疯狂的事情,就这样做:


void bar(Foo &foo)
{
    // ...
}

回答by Johan Lundberg

With C++11 shared_ptrand enable_shared_from_thisis now in the standard library. The latter is, as the name suggests, for this case exactly.

使用 C++11 shared_ptrenable_shared_from_this现在在标准库中。顾名思义,后者正是这种情况。

http://en.cppreference.com/w/cpp/memory/shared_ptr

http://en.cppreference.com/w/cpp/memory/shared_ptr

http://en.cppreference.com/w/cpp/memory/enable_shared_from_this

http://en.cppreference.com/w/cpp/memory/enable_shared_from_this

Example bases on that in the links above:

示例基于以上链接中的内容:

struct Good: std::enable_shared_from_this<Good>{
    std::shared_ptr<Good> getptr() {
        return shared_from_this();
    }
};

use:

用:

std::shared_ptr<Good> gp1(new Good);
std::shared_ptr<Good> gp2 = gp1->getptr();
std::cout << "gp2.use_count() = " << gp2.use_count() << '\n';

回答by Tyler

The function accepting a pointer wants to do one of two behaviors:

接受指针的函数想要执行以下两种行为之一:

  • Own the objectbeing passed in, and delete it when it goes out of scope. In this case, you can just accept X* and immediately wrap a scoped_ptr around that object (in the function body). This will work to accept "this" or, in general, any heap-allocated object.
  • Share a pointer(don't own it) to the object being passed in. In this case you do notwant to use a scoped_ptr at all, since you don't want to delete the object at the end of your function. In this case, what you theoretically want is a shared_ptr (I've seen it called a linked_ptr elsewhere). The boost library has a version of shared_ptr, and this is also recommended in Scott Meyers' Effective C++ book (item 18 in the 3rd edition).
  • 拥有传入的对象,并在超出范围时将其删除。在这种情况下,您可以只接受 X* 并立即将 scoped_ptr 包裹在该对象周围(在函数体中)。这将适用于接受“this”,或者一般来说,任何堆分配的对象。
  • 分享一个指针(不拥有它)在传递的对象。在这种情况下,你希望在所有使用scoped_ptr的,因为你不希望你的函数结束时删除对象。在这种情况下,您理论上想要的是 shared_ptr (我在其他地方看到它称为linked_ptr)。boost 库有一个 shared_ptr 版本,这也在 Scott Meyers 的 Effective C++ 书(第 3 版中的第 18 项)中推荐。

Edit:Oops I slightly misread the question, and I now see this answer is not exactly addressing the question. I'll leave it up anyway, in case this might be helpful for anyone working on similar code.

编辑:哎呀我有点误读了这个问题,现在我看到这个答案并没有完全解决这个问题。无论如何,我都会保留它,以防这对任何处理类似代码的人都有帮助。