27-二阶构造模式
关于构造函数
- 类的构造函数用于对象的初始化
- 构造函数与类同名并且没有返回值
- 构造函数在对象定义时自动被调用
【范例代码】异常的构造函数
#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(int argc, const char* argv[]) {
Test t1(1, 2);
if (t1.status()) {
printf("t1.mi = %d\n", t1.getI());
printf("t1.mj = %d\n", t1.getJ());
}
return 0;
}
- 只提供自动初始化成员变量的机会
- 不能保证初始化逻辑一定成功
- 执行return语句后构造函数立即结束
【温馨提示】构造函数能决定的只是对象的初始状态,而不是对象的诞生。
半成品对象
- 初始化操作不能按照预期完成而得到的对象
- 半成品对象是合法的C++对象,也是Bug的重要来源
二阶构造
工程开发中的构造过程可分为:
- 资源无关的初始化操作,不可能出现异常情况的操作
- 需要使用系统资源的操作,可能出现异常情况,如:内存申请、访问文件等
二阶构造示例:
class TwoPhaseCons {
private:
TwoPhaseCons() { // 第一阶段构造函数
}
bool construct() { // 第二阶段构造函数
return true;
}
public:
static TwoPhaseCons* NewInstance(); // 对象创建函数
};
TwoPhaseCons* TwoPhaseCons::NewInstance() {
TwoPhaseCons* ret = new TwoPhaseCons();
// 若第二阶段构造失败,返回NULL
if (!(ret && ret->construct())) {
delete ret;
ret = NULL;
}
return ret;
}
【范例代码】二阶构造初探
#include <stdio.h>
class TwoPhaseCons {
private:
TwoPhaseCons() { // 第一阶段构造函数
}
bool construct() { // 第二阶段构造函数
return true;
}
public:
static TwoPhaseCons* NewInstance(); // 对象创建函数
};
TwoPhaseCons* TwoPhaseCons::NewInstance() {
TwoPhaseCons* ret = new TwoPhaseCons();
// 若第二阶段构造失败,返回 NULL
if (!(ret && ret->construct())) {
delete ret;
ret = NULL;
}
return ret;
}
int main(int argc, const char* argv[]) {
TwoPhaseCons* obj = TwoPhaseCons::NewInstance();
printf("obj = %p\n", obj);
delete obj;
return 0;
}