#include <iostream>
using namespace std;
class Test
{
public:
Test()
{
printf("construct ..\n");
}
~Test()
{
printf("destruct...\n");
}
};
Test Get()
{
Test t = Test();
return t;
}
int main(int argc, char *argv[])
{
Test t = Get();
return 0;
}
the console output is :
$ g++ -g -Wall -O0 testdestructor.cc
$ ./a.out
construct ..
destruct...
No. You never need to explicitly call a destructor (except with placement new ). A class's destructor (whether or not you explicitly define one) automagically invokes the destructors for member objects. They are destroyed in the reverse order they appear within the declaration for the class.
The destructor is being called three times, for a , lol and b . In your case, a and b are instantiated using the default constructor .
According to the linked question, this is because the destructor is called multiple times for the pointer member, a consequence of the copy constructor being called multiple times when copying, causing an attempted deallocation of memory already deallocated.
Destructors are called when one of the following events occurs: A local (automatic) object with block scope goes out of scope. An object allocated using the new operator is explicitly deallocated using delete . The lifetime of a temporary object ends.
Its because of copy-elision by the compiler when you return the value from the function. In this case, the copy-elision is called RVO - Return Value Optimization.
See these
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