0

In the following example I tried to wrap this pointer into an std::shared_ptr (for instance for sending to a composite object as a parent pointer).

#include <iostream>
#include <memory>

class MyClass {
public:
    MyClass() { std::shared_ptr<MyClass> ptr(this); std::cout << (long long)ptr.get() << std::endl; }
    ~MyClass() { std::cout << (long long)this << "del" << std::endl; }
    int field;
};

int main() {
    MyClass* instance = new MyClass;
    std::cout << (long long)instance << "assign" << std::endl;
    instance->field = 5;
    delete instance;
    return 0;
}

The code issues the following output

140736965201520
140736965201520del
140736965201520assign
140736965201520del

According to the output, I can suppose, that the object was deleted twice. Furthermore, it was deleted after the shared_ptr was deleted (in the constructor).

Any suggestions on how to wrap the this into a shared_ptr and pass to others?

arsdever
  • 1,000
  • 6
  • 24
  • 6
    See [`std::enable_shared_from_this`](https://en.cppreference.com/w/cpp/memory/enable_shared_from_this) – NathanOliver Mar 02 '20 at 20:31
  • The flag duplicate isn't correct. I asked about using it from the constructor. But as you can see in the post it says, that the method isn't correct when you try to get it from the constructor – arsdever Mar 03 '20 at 19:52

0 Answers0