Junchen said:
If an exception is thrown, will the memory allocated in the heap be
released? And what's the underlying mechanism ? Thanks in advance.
Let me try to refine your question.
If an exception gets thrown during a construction of an object being
created with new, then yes, the memory for the object itself is
deallocated. Just as it was allocated with the appropriate operator
new function for that object, so will it be deleted with the
matching operator delete. This is the only time that the
so-called "placement delete" operator (one with args other
than just the pointer) is called.
It is however incumbent for the class designer to make sure that
any other subobjects or things allocated in the course of construction
are safe in the light of the exception. Of course if you design
your subobjects to be well behaved (like standard vector and
string classes or well designed user classes) this is taken
care for you. If you do your own dynamic allocation, you
need to clean up after youself.
For example
class MyClass {
char* internal;
public:
MyClass() {
internal = new char[some_non_constant];
throw "something";
}
};
MyClass* = new MyClass;
Here the memory for MyClass will be deallocated. However
the chars I new in the constructor will not be. So I
could handle the exception:
MyClass() {
try {
internal = new char[some_non_constant];
} catch(...) {
//yech
delete [] internal;
throw; // rethrow exception
}
}
But that's ugly. Of course you'll note that the rule of three
implies you also need to implement copy constructors, copy assignment
operators and destructors to handle the "internal" pointer.
Now if internal is a string, I could use std::string.
If internal was just some byte array, I could use vector.
Since vector has proper semantics for copying and destruction
I do not need to worry about it.
MyClass {
std::vector<char> internal;
public:
MyClass() : internal(some_non_constant) {
throw "something"
}
};
Voila.