Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why has the destructor been called only once?

Tags:

c++

destructor

#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...

like image 504
qiuxiafei Avatar asked Jun 21 '11 07:06

qiuxiafei


People also ask

Is destructor called only once?

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.

How many times destructor is called?

The destructor is being called three times, for a , lol and b . In your case, a and b are instantiated using the default constructor .

Can a destructor be called multiple times?

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.

Why is my destructor being called?

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.


1 Answers

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

  • Return Value Optimization
  • Copy elision
like image 78
Nawaz Avatar answered Sep 17 '22 08:09

Nawaz