异常的构造函数、二阶构造模式
#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的重要来源
-二阶构造是人为的把初始化过程分为两部分,确保创建的对象都是完整初始化的