Its a very common problem in C++ that if a class's constructor throws an exception (say
memory allocation exception) how we should handle it. Think about the following piece of code.
Here class A's constructor has thrown an exception.. so the best way to handle such situation is to instantiate A inside a try block...if exception is thrown in the constructor of A, i will be destroyed by stack unwinding and the thrown exception will be caught... trycatch block in exception is very important as constructor cannot return anything to indicate to the caller that something wrong has happened...
Lets consider the following case.
Here in class A we have two dynamically allocated char array. Now suppose while constructing A, the system was able to successfully construct the first char array, i.e. str1. However, while allocating the memory of str2, it throws OutOfMemory exception. As we know the destructor of an object will be called only if the object is fully constructed. But in this case the object is not fully constructed. Hence even if we release the memory in the destructor of A, it will never be called in this case. So what we will have is that the stack based pointers, i.e. str1 and str2 will be deleted because of stack unwinding. But the memory that have been allocated in the Heap won’t be destroyed. Hence we will have two blocks of heap memory ( one for the str1 that is 100 bytes long and the other for whatever have been allocated by str2 before the exception being thrown) which are not referenced by any pointer (str1 and str2 which have already been destroyed by the stack unwinding). Hence it is a case of memory leak.
Now the question is how can we handle the above situation. We can do it as follows.
But the best way to handle this kind of situation in modern C++ is to use auto_ptr/shared_ptr.
Look at the following piece of code to know how we have used boost’s shared pointer to avoid
memory leaks in the C++ constructor.
In Symbian C++, it is handled by a concept called two phase constructor... (it came into the
picture because there was no template concept in earlier Symbian C++, and hence there was
no auto_ptr)... in this process, if we want to create a dynamic memory allocation at the heap
pointed by say *pMem, then in the first phase of construction we initialize the object pointed by
pMem;. obviously this cannot throw exception... We then push this pMem to the cleanup stack...
and in the second phase of construction, we allocate memory pointed by pMem... so, if the
constructor fails while allocating memory, we still have a reference of pMem in the cleanup
stack... we just need to pop it and destroy it... hence there is no chance of memory leak...