【问题标题】:Why one may need a shared_from_this instead of directly using this pointer?为什么需要一个 shared_from_this 而不是直接使用 this 指针?
【发布时间】:2019-06-07 14:48:00
【问题描述】:

看这里的第二个答案: What is the need for enable_shared_from_this?

它说: "简短的回答:当你需要在对象本身内部使用现有的共享指针来保护这个对象时,你需要 enable_shared_from_this。

您可以简单地从对象中分配和复制一个 shared_ptr,因为您按原样处理 shared_ptr 变量。"

然后在最后一行写着: “以及何时以及为什么需要一个指向 this 而不仅仅是 this 的共享指针,这完全是另一个问题。例如,它广泛用于回调绑定的异步编程。”

在这篇文章中,我想确切地问另一个问题。 “enable_shared_from_this”和“shared_from_this”的用例是什么?

【问题讨论】:

    标签: c++11


    【解决方案1】:

    一个简单的用例是确保this 在某些异步或延迟操作结束之前一直存在:

    class My_type : public std::enable_shared_from_this<My_type> {
    
    public:
      void foo() {}
    
      void perform_foo() {
        auto self = shared_from_this();
        std::async(std::launch::async, [self, this]{ foo(); }); 
      }
    };
    

    boost::asio 在他们的示例中大量使用了这种技术: https://www.boost.org/doc/libs/1_66_0/doc/html/boost_asio/example/cpp11/allocation/server.cpp

    【讨论】:

      猜你喜欢
      • 2010-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-15
      • 2021-12-07
      相关资源
      最近更新 更多