C++之二阶构造模式

前言:C++中经常会因为调用系统资源失败导致出现BUG,所以在类调用构造函数需要分配系统资源时会出现BUG,从而导致类对象虽然被创建,但是只是个半成品,为了避免这种情况需要使用二阶构造模式

 

                      二阶构造模式

源码如下

 1 // 二阶构造.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include<iostream>
 6 
 7 using namespace std;
 8 
 9 class test
10 {
11 private:
12     int d;
13     test();//一阶构造,构造不会产生BUG的赋值等操作
14     bool construct();//二阶构造,构造申请系统资源,内存申请
15 public:
16     //静态函数,巧妙在于静态函数可以访问私有成员
17     //且无需对象即可调用
18     static test* NewInstance();//总构造函数
19 };
20 
21 int main()
22 {
23     test *p = test::NewInstance();
24 
25     cout << p << endl;
26 
27     return 0;
28 }
29 
30 //一阶构造,构造不会产生BUG的赋值等操作
31 test::test()
32 {
33 
34 }
35 
36 //二阶构造,构造申请系统资源,内存申请
37 bool test::construct()
38 {
39     return 1;
40 }
41 
42 //总构造函数
43 test* test::NewInstance()
44 {
45     test *ret = new test;//一阶构造
46 
47     //一阶分配失败或二阶分配失败
48     //删除半成品对象并置空
49     if (!(ret&&ret->construct()))
50     {
51         delete ret;
52         ret = NULL;
53     }
54 
55     return ret;
56 }

 

posted on 2017-08-15 01:41  么么打123  阅读(363)  评论(0编辑  收藏  举报