看看這個代碼:當使用複製構造函數保存它的變量被賦予一個新變量時,以前的對象是否被銷燬?
#include <iostream>
using namespace std;
class A {
private:
int _x;
int _id;
static int count;
public:
A(int x) : _x(x) {
this->_id = A::count++;
cout << "Object with id " << this->_id
<< " has been created." << endl;
}
~A() {
cout << "Object with id " << this->_id
<< " has been destroyed." << endl;
}
int get_x(void) {
return this->_x;
}
A add(A& object) {
A tmp(this->_x + object._x);
return tmp;
}
};
int A::count = 1;
int main(void) {
A object_1(13);
A object_2(5);
A object_3(12);
object_3 = object_1.add(object_2);
cout << object_3.get_x() << endl;
return 0;
}
下面是該程序的輸出:
Object with id 1 has been created.
Object with id 2 has been created.
Object with id 3 has been created.
Object with id 4 has been created.
Object with id 4 has been destroyed.
18
Object with id 4 has been destroyed.
Object with id 2 has been destroyed.
Object with id 1 has been destroyed.
我不明白髮生了什麼ID爲3到對象?它絕對是被創造出來的,但是我沒有看到線條告訴我它曾經被毀壞過。你能告訴我這裏發生了什麼事嗎?
順便問題,那爲什麼當我使用return 0
,析構函數正常工作,但是當我使用exit(EXIT_SUCCESS)
我沒有看到Object with # has been destroyed
印在屏幕上,儘管析構函數永遠不會被調用。
您的輸出不完整,因爲您沒有跟蹤複製構造函數。看看add函數和它返回的結果。 – PaulMcKenzie
'exit()'不調用析構函數。根據定義。如果你想調用析構函數,你從main返回。這就是語言的工作原理。 –
@MikhailR。請參閱[無優化](http://rextester.com/SLKNSX2722)。現在看到[優化啓用](http://rextester.com/EXTKL92760)。注意不同的輸出,一個調用複製構造函數,另一個不調用。 – PaulMcKenzie