#include<iostream>
using namespace std;
class mini
{
public:
mini() { cout << "mini()"; }
~mini() { cout << "~mini()"; }
};
class test
{
public:
mini ret()
{
return *(new mini());
}
};
int main()
{
test a;
a.ret();
cout << "end of block";
}
Output:
mini()~mini()end of block
Why is ~mini() run here before the end of the block? Or rather at all... If I change the output of the method to mini* then it doesn't get removed. I understand stack objects do get deleted, but I'm new'ing here.
Consider what happens here
mini ret()
{
return *(new mini());
}
ret() is a function returning mini by-value.
new mini() allocates mini on the heap. return *(new mini()); returns a copy of it by-value. So what is printed is the construction of mini on the heap and a destruction of its copy on the stack at the end of the full-expression where ret() is called.
To visualize it, implement a copy constructor:
#include<iostream>
using namespace std;
class mini
{
public:
mini() { cout << "mini()\n"; }
mini(const mini&) { cout << "mini() copy\n"; }
~mini() { cout << "~mini()\n"; }
};
class test
{
public:
mini ret()
{
return *(new mini());
}
};
int main()
{
test a;
a.ret();
cout << "end of block\n";
}
Prints
mini()
mini() copy
~mini()
end of block
So you're right, the original new'd mini is never deleted (leaked).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With