Exceptions in Constructors

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.