今天我對我的一段程序代碼產生了懷疑,不能確定在循環體內創建的對象在一次循環結束時是否會調用析構函數,於是我親手測試了一下:
#include <cstdlib>
#include <iostream>
using namespace std;
class A{
public:
A(){
cout << "A()" <<endl;
}
virtual ~A(){
cout << "~A()" << endl;
}
void seta(int n){
a = n;
}
private:
int a;
};
A fun(){
A a;
a.seta(5);
return a;
}
/*
*
*/
int main(int argc, char** argv) {
for(int i = 0; i < 5; i++){
cout << "begin"<<endl;
A a = fun();
cout << "end"<<endl;
}
cout << "for end" << endl;
return 0;
}
上面的代碼可以知道,一次循環後對象是否會及時析構。運行結果如下圖
分析上面的打印信息,我們會發現在賦值前系統會調用析構函數將上一次循環的對象釋放掉。而且循環結束後,我們創建的對象全部得到了釋放。所以這樣的調用不會引起對象沒有析構導致的內存泄漏,所以我的擔心是多餘的。