Bloomberg LP Interview Question
Software Engineer / DevelopersWhat if I simply do this,
class A{
int* x;
int* y;
int* z;
public:
A(){
try{
x = new int(10);
y = new int(11);
z = new int(12);
}catch(...){
delete x;
delete y;
delete z;
}
}//end of A constructor
~A(){
delete x;
delete y;
delete z;
}
};
you cant do like this.
The better way is to put each new inside nested try catch blocks. If there is an exception in allocating memory for x then doing what you did would try to delete y and z which are not allocated when x is getting allocated.
try {
x = new int(10);
try{
y = new int(11);
}
catch(...)
{
delete x;
delete y;
}
}
catch(...)
{
delete x;
}
}
Read this: gotw[dot]ca/gotw/066[dot]htm
They have explained why do you need function try blocks for constructors. Somewhere in that article.. it says if exception occurs in function try block then whatever objects that were successfully created will be destructed by calling their destructors.
// Example 1(a): Constructor function-try-block
//
C::C()
try
: A ( /*...*/ ) // optional initialization list
, b_( /*...*/ )
{
}
catch( ... )
{
// We get here if either A::A() or B::B() throws.
// If A::A() succeeds and then B::B() throws, the
// language guarantees that A::~A() will be called
// to destroy the already-created A base subobject
// before control reaches this catch block.
}
use a smart pointer.
- infinity April 22, 2010