Constructors and destructors are interesting creatures. There are literally hundreds of applications for their uses.
Here is an interesting use for the constuctor/destructor team, a mechanism that is very handy for cleaning up code and tying up loose ends in the process.
Consider this:
Assume you are writing a function in a class that processes highly volatile data. There are many times during it's execution where something could go wrong. Using a nested helper class, you clean up the interface and also avoid errors using a definite mechanism like this one.
Code:
class Processor {
public:
bool Process(void * data){
FatalErrorTracker fet(this);
//...code
if(!condition)
return false;
//...code
if(!condition)
return false;
//...code
if(!condition)
return false;
//...code
if(!condition)
return false;
fet.disable();
return true;
}
private:
class FatalErrorTracker {
public:
FatalErrorTracker (Processor * p){
processor = p;
}
void disable(){
processor = NULL;
}
~FatalErrorTracker (){
if(processor == NULL) return;
processor->close_valve();
processor->bad_error = true;
processor->initiate_shutdown();
}
private:
Processor * processor;
};
};
As you can see, until we reach the end of the function and disable the FatalErrorTracker, any exit will result in the execution of it's destructor, an emergency shutdown of sorts. The constructors main role here is to store a pointer to the processor object, to do so without calling a member function, and besides, the fact that this object cannot be contructed without that pointer makes it very clear the intent of the class.