More effective C + + clause 9 use destructor to avoid leaking resources

Source: Internet
Author: User

1. "When the function throws an exception, the execution of the current function is paused, and the matching catch statement begins to be found." First check whether the throw itself is inside the try block, and if so, check the catch statement associated with the try block to see if one of them matches the object being thrown. If a matching catch is found, the exception is handled, and if it is not found, it exits the current function (frees the current function's memory and revokes the local object) and continues to look in the calling function. ("C + + Primier") This is called stack unwinding.

2. Once an exception is thrown during the execution of the function, the execution of the next statement is stopped, the executing of the TRY block (the statement after the throw within the try block is no longer executed) and the search for a matching catch statement is made, and the local object that has been created is properly revoked during the step out of the try block. Runs a destructor for the local object and frees up memory.

3. If the memory is requested in the heap before throw, and the statement that frees the memory happens after the throw statement, the statement will not perform a memory leak if an exception is thrown.

4. The workaround is to encapsulate the pointer type in a class and free memory in the destructor for that class. This way, even if an exception is thrown, the destructor of the class will run and the memory can be disposed appropriately. The C + + standard library provides a class template called Auto_ptr, which is used to accomplish this function.

More effective C + + clause 9 use destructor to avoid leaking resources

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.