我編寫了一個簡單的程序,以瞭解更多關於在C++中創建和銷燬對象的順序(使用Visual Studio 2015)。那就是:C++中的對象創建和銷燬順序
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
A(string name)
: name(name)
{
cout << "A(" << name << ")::constructor()" << endl;
}
~A()
{
cout << "A(" << name << ")::destructor()" << endl;
}
private:
string name;
};
class C
{
public:
C(string name, A a)
: name(name), a(a)
{
cout << "C(" << name << ")::constructor()" << endl;
}
~C()
{
cout << "C(" << name << ")::destructor()" << endl;
}
private:
string name;
A a;
};
class B
{
public:
B(string name)
: name(name)
{
cout << "B(" << name << ")::constructor()" << endl;
}
~B()
{
cout << "B(" << name << ")::destructor()" << endl;
}
private:
string name;
A a1{"a1"};
A a2{"a2"};
C c1{"c1", a1};
A a3{"a3"};
};
int main()
{
B b("b1");
return 0;
}
輸出驚訝我一點點(在a1
S):
A(a1)::constructor()
A(a2)::constructor()
C(c1)::constructor()
A(a1)::destructor()
A(a3)::constructor()
B(b1)::constructor()
B(b1)::destructor()
A(a3)::destructor()
C(c1)::destructor()
A(a1)::destructor()
A(a2)::destructor()
A(a1)::destructor()
要詳細瞭解了事情的原委我增加了有關對象的實例的信息:
A(string name)
: name(name)
{
cout << "A(" << name << ")::constructor(), this = " << this << endl;
}
~A()
{
cout << "A(" << name << ")::destructor(), this = " << this << endl;
}
結果更令人驚訝:
A(a1)::constructor(), this = 0039FB28
A(a2)::constructor(), this = 0039FB44
C(c1)::constructor()
A(a1)::destructor(), this = 0039F8A8
A(a3)::constructor(), this = 0039FB98
B(b1)::constructor()
B(b1)::destructor()
A(a3)::destructor(), this = 0039FB98
C(c1)::destructor()
A(a1)::destructor(), this = 0039FB7C
A(a2)::destructor(), this = 0039FB44
A(a1)::destructor(), this = 0039FB28
也就是說,爲什麼a1
的構造函數只叫一次和析構函數3次?我通過值a
所以顯然至少創建了1個臨時對象,但請在和時向我解釋多少個A
實例被創建和銷燬?
你沒有註釋過很多其他類的構造函數,所以你只能看到部分圖片。 –
@KerrekSB你是指打印出B和C類的'this'值嗎?或者是什麼? – NPS
編譯器正在添加一些你看不到的默認構造函數。 – Galik