获得boost::shared_ptr。

[英]Getting a boost::shared_ptr for this


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:

我在代码中大量使用boost:shared_ptr。实际上,堆上分配的大多数对象都由shared_ptr持有。不幸的是,这意味着我不能将它传递到任何需要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_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.

这里有两个问题。首先,这不会编译,因为shared_ptr的T*构造函数是显式的。其次,如果我强制它使用bar(boost: shared_ptr (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?

这就引出了我的问题:是否有任何标准模式可以从这些对象中的一个方法中获取现有共享指针的副本?使用插入式引用计数是我唯一的选择吗?

6 个解决方案

#1


102  

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.

您可以从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:::绑定到shared_from_this()而不是这个,这是一个好主意。它将确保对象不会被释放。

#2


19  

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传递给函数的惟一时间是当您希望将对象的所有权传递给函数时,或者希望函数复制指针时。

#3


14  

boost has a solution for this use case, check enable_shared_from_this

boost为这个用例提供了一个解决方案,请检查enable_shared_from_this

#4


9  

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

你真的在酒吧里做更多的pFoo的共享拷贝吗?如果你内心没有做什么疯狂的事,那就这样做:


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

#5


5  

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

使用c++ 11 shared_ptr和enable_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';

#6


3  

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

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

  • Own the object being 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.
  • 拥有传入的对象,并在对象超出范围时删除它。在这种情况下,您可以只接受X*,并立即在该对象(在函数体中)包围一个scoped_ptr。这将工作于接受“This”或一般地接受任何堆分配的对象。
  • Share a pointer (don't own it) to the object being passed in. In this case you do not want 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).
  • 向被传入的对象共享一个指针(不要拥有它)。在这种情况下,您根本不想使用scoped_ptr,因为您不想在函数的末尾删除对象。在这种情况下,理论上需要的是shared_ptr(我在别处见过它被称为linked_ptr)。boost库有shared_ptr的一个版本,这在Scott Meyers的有效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.

编辑:哦,我读错了问题,现在我看到这个答案并没有完全解决问题。无论如何,我都将它保留下来,以防这对任何使用类似代码的人都有帮助。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2008/09/26/13368a334350082b41db4b94ea74cd87.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号