Effective C++ item 17: Store newed objects in smart pointers in standalone statements.

Sometimes if you try to do multiple things in one statement, you should think carefully about abnormal behavior especially exceptions. For example:

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

With this statement, if compile choose to do things in following order:

  1. Execute “new Widget”.
  2. Call priorigy().
  3. Call the std::tr1::shared_ptr constructor.
    In addition, if the call to priority yields an exception, you are running into resource leak. Because the pointer returned from “new Widget” will be lost before it’s put into shared_ptr.

So what’s the suggestion? Don’t combine too many calls into one statement, especially dangerous ones like new objects.

“Effective C++” Third Edition by Scott Meyers.