Suppose there is this code:
class CFoo
{
public:
CFoo()
{
iBar = new CBar();
}
private:
CBar* iBar;
};
....
CFoo* foo = new CFoo();
When the above line is executed, first memory will be allocated to hold the CFoo object. But then if the line new CBar() throws an exception (due to lack of memory) does the system automatically deallocate the memory that was previously allocated to the CFoo object? I presume it must, but cannot find any explicit reference saying so. If it doesn't how can the memory be deallocated by the coder as it will not have been assigned to foo?
Yes, the memory allocated for the CFoo
object will be freed in this case.
Because the exception due to the failed allocation causes the CFoo
constructor to fail to complete successfully the new-expression is guaranteed to free the memory allocated for that CFoo
object.
This guarantee is specified in 5.3.4 [expr.new] / 17 of ISO/IEC 14882:2003.
Note, that it is always advisable to assign the result of a dynamic allocation to a smart pointer to ensure proper clean up. For example, if there was further code in CFoo
constructor and that threw an exception the CBar
object already successfully allocated earlier in the constructor would be leaked.
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