Remember:
- Stores the Newd object in a smart pointer in a separate statement. If you do not, once an exception is thrown, it is possible to cause an imperceptible resource leak.
intPriority ();voidProcesswidget (std::tr1::shared_ptr<widget> PW,intPriority );//compilation error Because the shared_ptr constructor is a explicit constructor and cannot be implicitly convertedProcesswidget (NewWidget, priority ());//the compilation is correct, but there is a potential problem. //before calling Processwidget, the compiler must create code that does the following three things//1. Call priority ()//2. Execute the new Widget//3. Call the Tr1::shared_ptr constructor//The order in which the C + + compiler completes the calculation of function parameters is indeterminate, so if the order of execution is//1. Execute the new Widget//2. Call Priority ()//3. Call the Tr1::shared_ptr constructor//In the event that the priority () call results in an exception, the pointer returned by the new widget is lost because it has not been placed in the shared_ptr. Processwidget (Std::tr1::shared_ptr<widget> (NewWidget), priority ());//the solution isStd::tr1::shared_ptr<widget> PW (NewWidget);p rocesswidget (PW, priority ());
Effective C + + clause 17: Placing newd objects into smart pointers with stand-alone statements