如果您已经有一个 std::shared_ptr 供您使用,那么 std::enable_shared_from_this 有多大用处?

How useful is std::enable_shared_from_this if you already have a std::shared_ptr at your disposal?

我偶然发现了 std::enable_shared_from_this,尤其是这个 similar question,但我仍然不明白有什么意义

重复出现的例子如下:

class Y: public 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();
}

但是我不明白这个例子,如果我遇到这种情况我会这样做:

int main()
{
    shared_ptr<Y> p(new Y);
    shared_ptr<Y> q = p; // Results in exactly the same thing
}

谢谢

编辑:我认为关闭问题的人没有理解我的意图。 post 被标记为另一个 post 的副本,而 这个 post 的第一行 链接到相同的 "other post" .我有一个 so-called 副本没有答案的问题。

具体来说,需要将 class 实现 enable_shared_from_this 创建为 std::shared_ptr。所以你可以访问那个 shared_ptr。我的问题是(在你的标题中),"Because you are forced to have a std::shared_ptr anyways, does keeping track of it actually renders std::enable_shared_from_this useless/redundant?"

立即想到两个用例spring:

  1. 它允许对象将自己交给其他东西,然后保持共享指针。对象本身不拥有共享副本。 shared_from_this的要点是给对象一个内部的weak_ptr.

  2. 由于传递共享指针是昂贵的(而且是多余的,当你知道它总是在调用堆栈中拥有时),标准做法是传递包含的对象作为引用。如果在调用堆栈的某个地方,你需要再次获取共享指针,你可以通过 shared_from_this.

  3. 来实现