Effective C++ 笔记 —— Item 17: Store newed objects in smart pointers in standalone statements.

Suppose we have a function to reveal our processing priority and a second function to do some processing on a dynamically allocated Widget in accord with a priority:

int priority();
void processWidget(std::tr1::shared_ptr<Widget> pw, int priority);

Consider now a call to processWidget:

processWidget(std::tr1::shared_ptr<Widget>(new Widget), priority());

Before processWidget can be called, then, compilers must generate code to do these three things:

  1. Call priority. 
  2. Execute “new Widget”. 
  3. Call the tr1::shared_ptr constructor

C++ compilers are granted considerable latitude in determining the order in which these things are to be done. (This is different from the way languages like Java and C# work, where function parameters are always evaluated in a particular order.) The “new Widget” expression must be executed before the tr1::shared_ptr constructor can be called, because the result of the expression is passed as an argument to the tr1::shared_ptr constructor, but the call to priority can be performed first, second, or third. If compilers choose to perform it second (something that may allow them to generate more efficient code), we end up with this sequence of operations:

  1. Execute “new Widget”.
  2. Call priority.
  3. Call the tr1::shared_ptr constructor.

But consider what will happen if the call to priority yields an exception. In that case, the pointer returned from “new Widget” will be lost.

The way to avoid problems like this is using a separate statement

std::tr1::shared_ptr<Widget> pw(new Widget); // store newed object in a smart pointer in a standalone statement

processWidget(pw, priority()); // this call won’t leak

Things to Remember:

  • Store newed objects in smart pointers in standalone statements. Failure to do this can lead to subtle resource leaks when exceptions are thrown.
原文地址:https://www.cnblogs.com/zoneofmine/p/15221764.html