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);

However, we cannot use this function in this way:

processWidget(new Widget, priority());

Since tr1::std::shared_pointer's constructor taking a raw pointer is explicit, so there is no implicit conversion from the raw pointer returned by the expression new Widget to the tr1::shared_ptr required by processWidget.
So we should modify the code as:

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

Although it is using object-managing resources here, this call may leak resources.

Let us focus on the first argument,

std::tr1::shared_ptr<Widget>(new Widget)

it consists of two parts :

  • Execution of the expression new Widget.
  • A call to the tr1::shared_ptr constructor.

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.
But the call to priority can be performed everywhere. If the compilers choose to perform it second , we end up with this sequence of operations :

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

Since the call to priority may yields an exception ,the pointer returned from new Widget will be lost, because it will not have been stored in the tr1::shared_ptr we were expecting would guard against resource leaks.

The way to avoid problem like this is simple : use a separate statement to create the Widget and store it in a smart pointer, the pass the smart pointer to processWidget:

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

processWidget(pw, priority());

Conclusion

Store new object in smart pointers in standalone statements.Failure to do this can lead to subtle resource leaks when exceptions are thrown.

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • ![Flask](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAW...
    极客学院Wiki阅读 8,190评论 0赞 3
  • 不知不觉易趣客已经在路上走了快一年了,感觉也该让更多朋友认识知道易趣客,所以就谢了这篇简介,已做创业记事。 易趣客...
    Physher阅读 4,136评论 1赞 2
  • 双胎妊娠有家族遗传倾向,随母系遗传。有研究表明,如果孕妇本人是双胎之一,她生双胎的机率为1/58;若孕妇的父亲或母...
    邺水芙蓉hibiscus阅读 4,162评论 0赞 2
  • 晴天,拥抱阳光,拥抱你。雨天,想念雨滴,想念你。 我可以喜欢你吗可以啊 我还可以喜欢你吗可以,可是你要知道我们不可...
    露薇霜凝阅读 1,424评论 1赞 2

友情链接更多精彩内容