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?