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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With