3
4

1 回答 1

2

核心问题就在这里,由于某种原因,并非代码库中的每个共享指针对其余代码都是“已知的”。

如果您有权访问已经给定的shared_ptr内容,则应始终shared_ptr<S> sp2 = sp1;按您所写的方式使用。使用std::enable_shared_from_this.

让我们看下面的例子:

struct S: std::enable_shared_from_this<S>
{   
    std::shared_ptr<S> getPtr() { return shared_from_this(); }
};  

// Here we have no interface for providing a shared_ptr, maybe
// code that we can't change or maintain or comes as callback from
// a library we want to use
void f( S* s ) 
{   
    // here we have no access to shared_ptr<S>...
    // so we need to have access to the unique counting instance
    // of all other shared_ptr which are pointing to this object
    std::shared_ptr<S> p3 = s->getPtr();
    std::cout << p3.use_count() << std::endl;

    // do some stuff....

}

int main()
{
    std::shared_ptr<S> p1 = std::make_shared<S>();
    std::cout << p1.use_count() << std::endl;

    // This example is useless, as you can directly use p1
    std::shared_ptr<S> p2 = p1->getPtr();
    std::cout << p1.use_count() << std::endl;
    std::cout << p2.use_count() << std::endl;

    // But if we have to use a interface, which is not providing access via shared_ptr like this:
    f(p1.get());
}  

这里要解决的关键问题是简单地访问公共“句柄”,它连接我们系统中的所有其他 shared_ptr IF!我们根本无法访问任何 shared_ptr!

我们无法访问我们对象的任何现有 shared_ptr 的原因可能有很多:使用只允许原始指针但我们想在其余代码中使用共享 ptr 的旧接口,使用来自库的回调也只支持原始指针等。

使用std::enable_shared_from_this<S>有一些缺点:

您的接口不能再使用const S*了,因为创建一个新接口shared_ptr将修改std::enable_shared_from_this现在是您的类或结构的基类的数据。它还增加了对象的大小。

于 2019-06-13T18:26:16.157 回答