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

Kjuly
  • 34,476
  • 22
  • 104
  • 118
qiuxiafei
  • 5,827
  • 5
  • 30
  • 43
  • possible duplicate of [What are copy elision and return value optimization?](http://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization) – Luchian Grigore Oct 18 '12 at 17:06

5 Answers5

10

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

Nawaz
  • 353,942
  • 115
  • 666
  • 851
6

Compiler optimizations.

On other compilers/optimization settings, it might get called more than once.

See this compile: http://codepad.org/8kiVC3MM

Output:
1 construct ..
2 destruct...
3 destruct...
4 destruct...
5 destruct...

Note that the defined constructor wasn't called all those times because the compiler-generated copy constructor was called instead.

See this compile: http://codepad.org/cx7tDVDV

... where I defined an extra copy constructor on top of your code:

Test(const Test& other)
{
    printf("cctor\n");
}

Output:
1 construct ..
2 cctor
3 destruct...
4 cctor
5 destruct...
6 cctor
7 destruct...
8 destruct...

Merlyn Morgan-Graham
  • 58,163
  • 16
  • 128
  • 183
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.

Stephan
  • 4,187
  • 1
  • 21
  • 33
2

It's called return value optimization, or RVO.

Kirill Kovalenko
  • 2,121
  • 16
  • 18
2

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

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243