zoukankan      html  css  js  c++  java
  • 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.
  • 相关阅读:
    Java XML的总结(一)
    golang两个协程交替打印1-100的奇数偶数
    nat类型探测方法(排除法)
    janus-gateway 在macOS上的编译部署
    性能测试-并发和QPS
    基于etcd的Rabbitmq队列订阅负载均衡
    【python学习笔记】10.充电时刻
    【python学习笔记】9.魔法方法、属性和迭代器
    【python学习笔记】8.异常
    【python学习笔记】7.更加抽象
  • 原文地址:https://www.cnblogs.com/zoneofmine/p/15221764.html
Copyright © 2011-2022 走看看