Turn from: http://blog.51cto.com/9291927/1896411 One,
problems with constructors
There is a problem with the constructor:
A, the constructor only provides an opportunity to initialize member variables automatically
B, there is no guarantee that the initialization logic will succeed, such as requesting system resources may fail
C. The constructor ends immediately after executing the return statement
Constructors can create objects that are semi-finished objects, which are legitimate objects, but are a source of program bugs. Therefore, the second-order tectonic model is used in the actual engineering development process.
two or two-step tectonic mode
Because of the potential problems of constructors, the construction of class objects in real engineering development is as follows:
A, resource-independent initialization operation
Resource-independent initialization operations typically do not show exceptions
B, System resource-related operations
For system resource-related operations such as heap space requests, file access may fail.
The flow of the second order construction mode is as follows:
The second-order construction mode ensures that the created objects are fully initialized. Because class objects occupy a large amount of storage space in engineering practice, they generally need to be allocated in heap space, so the second-order construction mode constructs objects in a way that assigns objects to stacks and global data extents in the constructor, preserving only the construction of objects created in the heap space.
Second-order Construction mode Instance code:
| 1234567891011121314151617181920212223242526272829303132333435363738394041 |
#include <stdio.h> classTwoPhaseCons {private: TwoPhaseCons() // 第一阶段构造函数 { } boolconstruct() // 第二阶段构造函数 { returntrue; }public: staticTwoPhaseCons* NewInstance(); // 对象创建函数}; TwoPhaseCons* TwoPhaseCons::NewInstance() { TwoPhaseCons* ret = newTwoPhaseCons(); // 若第二阶段构造失败,返回 NULL if( !(ret && ret->construct()) ) { deleteret; ret = NULL; } returnret;} intmain(){ TwoPhaseCons* obj = TwoPhaseCons::NewInstance(); printf("obj = %p\n", obj); deleteobj; return0;} |
C + + second-order constructors