小编Bha*_*ura的帖子

对enable_shared_from_this有什么需求?

我是C++ 11的新手,我遇到了enable_shared_from_this.我不明白它想要达到的目的是什么?所以我有一个使用enable_shared_from_this的程序.

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

~TestCase() { std::cout << "TestCase::~TestCase()"; }
};


int main()
{
std::shared_ptr<testcase> obj1(new TestCase);
std::shared_ptr<testcase> obj2 = obj1->getptr();
// The above can be re written as below
//  std::shared_ptr<testcase> obj2 = shared_ptr<testcase>(obj1);
}
Run Code Online (Sandbox Code Playgroud)

我的问题是当我需要一个指向'this'的指针时,为什么不使用obj本身.为什么要从该类的函数返回'this',比如使用getptr()然后返回shared_from_this()???? 我不明白.

第二个问题,如果不使用enable_shared_from_this,为什么dtor被调用两次会产生问题,崩溃!!!!

我可以绕过使用enable_shared_from_this的另一种方法是这样的.在TestCase类中添加它

  std::shared_ptr getptr1(shared_ptr obj) {
   return std::shared_ptr(obj);
  }
Run Code Online (Sandbox Code Playgroud)

从主要打电话给这个:

  std::shared_ptr bp2 = bp1->getptr1(bp1);
Run Code Online (Sandbox Code Playgroud)

并做了.我们不需要enable_shared_from_this.为什么在地球上我们需要它?

c++ boost shared-ptr c++11

5
推荐指数
2
解决办法
1036
查看次数

标签 统计

boost ×1

c++ ×1

c++11 ×1

shared-ptr ×1