Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two phase Construction in C++

Tags:

c++

sdk

I have as part of assignment to look into a development kit that uses the "two-phase" construction for C++ classes:

// Include Header
class someFubar{
public:
    someFubar();
    bool Construction(void);
    ~someFubar();
private:
    fooObject _fooObj;
}

In the source

// someFubar.cpp
someFubar::someFubar : _fooObj(null){ }

bool 
someFubar::Construction(void){
    bool rv = false;
    this->_fooObj = new fooObject();
    if (this->_fooObj != null) rv = true;
    return rv;
}

someFubar::~someFubar(){
    if (this->_fooObj != null) delete this->_fooObj;
}

Why would this "two-phase" be used and what benefits are there? Why not just instantiate the object initialization within the actual constructor?

like image 476
t0mm13b Avatar asked Jun 11 '10 09:06

t0mm13b


1 Answers

A document about Two Phase Construction.

The idea is that you cannot return a value from a constructor to indicate failure. The only way to indicate constructor failure is to throw an exception. This is not always desirable, not least because exception safety is a very complex topic.

So in this case the construction is split up: a constructor that does not throw, but also does not fully initialize, and a function that does the initialization and can return an indication of success or failure without (necessarily) throwing exceptions.

like image 163
Joris Timmermans Avatar answered Oct 05 '22 23:10

Joris Timmermans