1: When a class encounters an exception in the new process, the memory occupied by it will be deleted (the operator delete function will be called) (this is the responsibility of the compiler, and I have not done a good job myself, I will destroy it, so I will not bother others .). however, the Destructor will not be called.
2: If there is no problem with a new class, the delete task will be handed over to the programmer.
3: new char [], int [] and other methods to obtain the memory. If a failure returns null, the resource is released by the compiler, and the task is successfully released, the task is handed over to the programmer. therefore, it is generally necessary to check whether the return value of new is null.
So assume that the constructor and destructor in obj are as follows:
Obj ()
{
PA = new ();
PB = new B ();
PC = new C ();
}
~ Obj ()
{
Delete pA; //: it is not used as an empty check for convenience.
Delete pB;
Delete pC;
}
If an exception occurs in new C (), new A and new B () are correctly updated. The Compiler releases new C () memory by itself.
While the memory of new A () and new B () is originally ~ When obj () is released, an exception occurs in obj ,~ Obj () will cause memory leakage.
A better solution is:
Obj ()
{
Try {
PA = new ();
PB = new B ();
PC = new C ();
}
Catch (...)
{
Delete pA;
Delete pB;
Delete pC;
Throw; // continue to pass the exception. Inform the superior. I have encountered an exception here.
}
}
In this way, no matter which object has a problem, it can ensure that the new object can be released by the positive solution. (ps: this is exactly the explanation of more efficient C ++ Item 10 .)
The idea is that if an exception occurs, our task is to release the new memory !!!
In general, it is to release all new memory in the current function, that is, the memory of all new objects in this class.