What is the need for enable_shared_from_this?

Viewed 1880

I am new to C++11 and I came across enable_shared_from_this. I do not understand what it is trying to achieve? So I have a program that uses 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);
}

My question is when I need a pointer to 'this', why not use the obj itself. Why to return a 'this' from a function of that class like using getptr() and then returning shared_from_this()???? I do not understand.

Second question, if enable_shared_from_this is NOT used, why is the dtor called twice that creates a problem, a crash!!!!

Another way I can bypass using enable_shared_from_this is like this. Add this in class TestCase

  std::shared_ptr getptr1(shared_ptr obj) {
   return std::shared_ptr(obj);
  }

and from main make a call this this:

  std::shared_ptr bp2 = bp1->getptr1(bp1);

And done. We do not need enable_shared_from_this. Why on the earth do we need it??

2 Answers
Related