異常的建構函式、二階構造模式
阿新 • • 發佈:2021-07-01
#include <stdio.h> class Test { int mi; int mj; bool mStatus; public: Test(int i, int j) : mStatus(false) { mi = i; return; mj = j; mStatus = true; } int getI() {return mi; } int getJ() { return mj; } int status() { return mStatus; } }; int main() { Test t1(1, 2); if( t1.status() ) { printf("t1.mi = %d\n", t1.getI()); printf("t1.mj = %d\n", t1.getJ()); }return 0; }
建構函式中執行出錯,或者提前返回,出現的問題
為了解決此問題,我們引入二階建構函式
#include <iostream> #include <string> using namespace std; class test { private: int *m_pValue1; int *m_pValue2; test(){} //第一階段,內部可實現一些與資源無關的操作 bool construct() //第二階段,所有可能發生異常的操作都可放在這裡執行 { m_pValue1= new int(10); m_pValue2 = new int(20); if (!(m_pValue1 && m_pValue2)) //申請記憶體失敗,則返回false { return false; } return true; } public: static test* NewInstance() { test* ret = new test(); if ( (ret == NULL) || (!ret->construct()) ) { delete ret; //構造失敗或者第二階段失敗,就銷燬半成品物件 ret = NULL; } return ret; //否則返回已經生成完成的物件指標 } int getValue1() { return *m_pValue1; } int getValue2() { return *m_pValue2; } }; int main() { test *t = test::NewInstance(); //只能使用靜態成員函式生成類物件 if (!t) { cout << "Error" << endl; } else { cout << "t.getValue1() = " << t->getValue1() << endl; cout << "t.getValue2() = " << t->getValue2() << endl; } system("pause"); } ———————————————— 版權宣告:本文為CSDN博主「火焰山大白菜」的原創文章 原文連結:https://blog.csdn.net/lms1008611/article/details/81411413
-建構函式只能決定物件的初始化狀態
-建構函式中初始化操作的失敗不影響物件的誕生
-初始化不完全的半成品物件是Bug的重要來源
-二階構造是人為的把初始化過程分為兩部分,確保建立的物件都是完整初始化的