Let’s say we have some class with a constructor:
class MyClass
{
public:
MyClass()
{
//our code goes here
throw "OMG";//well, some code that throws an exception
}
};
Now, when an exception occurs, stack unwinding is being performed. I also know that if the exception is thrown from the constructor, the corresponding object’s destructor will not be called, because the object was never completely “created” in the first place.
I’m a little confused by this. To me that implies that the object is considered “created” only when the constructor finishes. But obviously, all the memory is allocated at some place before (or right after) the constructor is called, because we can manipulate the object’s members inside the constructor.
So when exactly is the object created in memory, and what happens to the memory of an object that caused the exception?
The memory is allocated before the body of the constructor.
If a constructor fails, the automatically allocated memory is freed.
And the accent of “automatically allocated” is important – if you have dynamically allocated memory in the constructor and the constructor fails (for example, you may have used
newbeforethrow "OMG"), this memory will leak.That’s because – you have allocated this memory, you need to free it.
You’re right, that the destructor is not called, but the destructor is not the one, which frees the memory, allocated for the auto members of a class.
It’s used (basically) to free memory, allocated by the user (in the constructor or somewhere else).
In other words, allocating memory for an object is different from the object’s construction.
Another example – if you create an object dynamically, like:
this will:
operator newMyObjSee, both things are different.