Alex Rivera | Logout

Why has the destructor been called only once?

Asked 2011-06-21T07:59:46.810
10
#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...

Edit
Report

2 Answers

6

I suppose the reason is return value optimization in 'Get'.

Have a look at http://en.wikipedia.org/wiki/Return_value_optimization

Actually your code is not the standard example, but maybe your compiler applies it here as well.

answered 2011-06-21T08:06:36.130
2

Try g++ -fno-elide-constructors (and define a copy constructor that prints a message).

answered 2011-06-21T08:08:55.783

Your Answer