Consider the following class:
struct MyClass {
int mId;
MyClass(int id): mId(id) {}
~MyClass() { std::cout << "deleting: " << mId << std::endl; }
};
And the usage:
std::shared_ptr<MyClass> p(new MyClass(0));
MyClass& m = *p;
m = MyClass(2);
The result is:
deleting: 2
deleting: 2
Please help me understanding:
MyClass(2)
objects (assumption made on the destructor logs)MyClass(0)
leak? Thank you.
There is no memory leak. This code:
m = MyClass(2);
creates a temporary object of type MyClass
which is copied into m
using the (default-generated) copy assignment operator of MyClass
, and then destructed. Eventually, p
runs out of scope and its destructor destroys the MyClass
instance to which is points (the one bound to m
).
If we spelled out all the implicit calls explicitly, this is happening:
// std::shared_ptr<MyClass> p(new MyClass(0));
tmp1.MyClass(0);
p.shared_ptr(&tmp1);
// MyClass& m = *p;
p.operator* ();
// m = MyClass(2);
tmp2.MyClass(2);
m.operator= (tmp2);
tmp2.~MyClass();
// p goes out of scope
p.~shared_ptr();
tmp1.~MyClass();