Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

c++ - Why has the destructor been called only once?

#include <iostream>

using namespace std;

class Test
{
public:
    Test()
    {   
        printf("construct ..
");
    }   

    ~Test()
    {   
        printf("destruct...
");
    }   
};

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...