C++ 匿名對象的生命週期

//匿名對象的生命週期
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;

class Point{
public:
    Point(){
        cout << "自定義的無參構造函數被調用了1" << endl;
    }
    ~Point(){
        cout << "自定義的析構函數被調用了2" << endl;
    }
};

void ProtectA(){
    //直接調用Point的類構造函數
    Point();
    //此時c++編譯器會自動生成匿名對象,
    //可是經過觀察發現  執行Point();同時調用無參構造函數和析構函數
    //說明c++編譯器發現後面沒有代碼調用這個匿名對象,因此馬上釋放了
}

void main(){
    ProtectA();

    system("pause");
}
相關文章
相關標籤/搜索