开发者

C++ destructor behaviour [duplicate]

This question already has answers here: Two calls to destructor (3 answers) Closed 8 years ago.

I tried the following program on Visual Studio 2010.

#include <iostream>
using namespace std;

class A {
public:
        int p;

        /*A(){
            cout << "Constructor A" << endl;
        }*/

        ~A(){
            cout << "Destructor in A" << endl;
        }
};

class D: public A
{
public: 

        /*D(){
            cout << "Constructor D" << endl;
        }*/

        ~D(){
            cout << "Destructor in D" << endl;
        }
};

int main()
{
    D d =  D();
    cout << "Exiting main" << endl;
}

The output that I got was -

Destructor in D
Destructor in A
Exiting main
Destructor in D
Destructor in A
开发者_如何学JAVA

I am not able to understand why the destructor of class D and A are being called before "Exiting main" statement is executed?

I tried another thing - I uncommented the Class D constructor in the code above, then the output was as I expected -

Constructor D
Exiting main
Destructor in D
Destructor in A

What am I missing here?


The line

D d =  D();

first creates a temporary, unnamed object, which then is copied to d. What you see is the temporary object being destroyed when the statement is ended. The named object d is destroyed when it goes out of scope, after main() is completed.

If you add a copy constructor to D you'll see that it is invoked.

When commenting out the constructor I think that you see the expected behaviour because the compiler can do some optimizations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜