Article 17: Insert a newed object into a smart pointer using an independent statement

Source: Internet
Author: User

 

Assume that a function is used to process the priority of a program, and another function is used to perform some priority processing on a Widget dynamically allocated:

Int priority (); // The priority function of the processing program.
Void processWidget (std: tr1: shared_ptr <Widget> pw, int priority); // This function performs priority processing on dynamically allocated widgets.

Call:

ProcessWidget (new Widget, priority (); // compilation failed! This constructor is explicit and cannot be implicitly converted to shared_ptr.

Therefore, you can write it as follows:

ProcessWidget (std: tr1: shared_ptr <Widget> (new Widget), priority (); // It can be compiled, but... resources may be leaked.

Consequence:Resource leakage may occur in the event of an exception.

Cause:

Before calling processWidget, the compiler must create code and perform three steps:

(1) Call prority ()

(2) Execute "new Widget"

(3) Call the tr1 "shared_ptr Constructor

However, the c ++ call sequence is different from that of java and c #, not in a specific order. The call to the priority function may be executed in the first, second, or third place. When the second bit is executed:

(1) Execute "new Widget"

(2) Call prority ()

(3) Call the tr1 "shared_ptr Constructor

If an exception occurs when calling prority, the pointer returned by "new Widget" will be lost, which will cause resource leakage.

Solution:Use the separation statement to write (1) create a Widget, (2) place it in a smart pointer, and then pass the smart pointer to processWidget:

Std: tr1: shared_ptr <Widget> pw (new Widget); // store the newed object with a smart pointer in a separate statement
ProcessWidget (pw, priority (); // This action will not cause leakage

Because the compiler has no freedom to rearrange the operations that span statements (only the compiler in the statement has that Degree of Freedom ).

 

 

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.