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.
  • 相关阅读:
    关于Oracle过程,函数的经典例子及解析
    describeType的使用
    Flash Pro CS5无法跳过注册Adobe ID的问题
    DOM的滚动
    Flex的LogLogger类
    浏览器无法打开Google服务
    as3中颜色矩阵滤镜ColorMatrixFilter的使用
    仿Google+相册的动画
    Flex中ModuleManager的一个bug
    有序的组合
  • 原文地址:https://www.cnblogs.com/zoneofmine/p/15221764.html
Copyright © 2011-2022 走看看