Effective C++ Item 17 Store newed objects in smart pointer in standalone statements

If you trying to do multiple things in one statement, you should think carefully abnormal behavior especially exceptions. Let's see an example:

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

What you expected might be

new Widget;
shared_ptr<Widget>(...);
priority();

But it may execute in the order of 

new Widget;
priority();
shared_ptr<Widget>(...);

if priority() yield exception, you are running into resource leak. Because the pointer will be lost before stored into shared_ptr.

So, what's the suggestion?

Just store newed object in smart pointer in standalone statement.

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

 

 

 

你可能感兴趣的:(statement)