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 ).