您的位置:首页 > 移动开发 > Objective-C

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

2014-02-28 15:37 507 查看
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());
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐