EC Note: Part III: 17. Use a separate statement to put the Newed object into a smart pointer

Source: Internet
Author: User

General smart pointers are initialized with a normal pointer, so it's easy to write the following code:

#include <iostream>

using namespace std;

intfunc1() {

    // function that returns an integer

}

voidFunc2(autoptr<int*> ptr, int t) {

    // Some operations

}

intmain() {

     func2 ( autoptr< Span style= "Color:teal" > < int * > (new int< Span style= "Color:teal" > ( 5 )), func1 ());

    // Other Operations

}

At first glance, this code seems to have no problems, but it is hidden.

When we call Func2, the arguments inside are required to operate, and there are three steps in the operation:

    1. int *t=new int (5);//Assuming the middle variable is t
    2. autoptr<int*> param (t);//Assuming the intermediate variable is param
    3. Func1 ();

We know that 11 will be called before 2, but the order of 3 calls is not necessarily.

Let's assume a situation where the call order is 1->3->2

Suppose we throw an exception when we call 3, when 1 has been called, that is, the memory has been allocated, but not successfully placed in the smart pointer. This block of memory is not automatically released. This causes a memory leak.

To avoid this situation, we can divide the process into two steps:

#include <iostream>

using namespace std;

intfunc1() {

    // function that returns an integer

}

voidFunc2(autoptr<int*> ptr, int t) {

    // Some operations

}

intmain() {

    autoptr < int *> param (new int ( 5 ));

func2(param,func1());

    // Other Operations

}

As long as you ensure that the initialization of the smart pointer is not interrupted, the vulnerability will naturally be lifted.

Even if Func1 throws an exception, when the smart pointer is initialized, the managed memory can be freed from the destructor.

EC Note: Part III: 17. Use a separate statement to put the Newed object into a smart pointer

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.