天天看點

匿名對象

什麼是匿名對象?

匿名對象可以了解為是一個臨時對象,一般系統自動生成的,如你的函數傳回一個對象,這個對象在傳回時會生成一個臨時對象。

匿名對象的生命周期(很重要!!!)

#include<iostream>

#include<vector>

using namespace std;

class p

{

public:

p() { num = 100; }

p(int n) :num(n) {};

int num;

};

p test()

//如你的函數傳回一個對象,這個對象在傳回時會生成一個臨時對象。

return p(520);//匿名對象,在執行完目前語句後,就被釋放

}

int main()

cout << test().num << endl;//執行完目前語句,函數test結束,匿名對象被釋放

p temp = test().num;//這裡是指派完後,匿名對象就被釋放了嗎???

cout << temp.num << endl;

system("pause");

return 0;

驗證匿名對象的生命周期:

p temp = test().num;//這裡是指派完後,匿名對象就被釋放了嗎???

大家可以先思考一下這個問題

驗證:

上一篇: 匿名函數
下一篇: 匿名函數