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.
  • 相关阅读:
    codechef Dynamic GCD [树链剖分 gcd]
    bzoj 4546: codechef XRQRS [可持久化Trie]
    bzoj 4835: 遗忘之树 [树形DP]
    bzoj 4033: [HAOI2015]树上染色 [树形DP]
    bzoj 4591: [Shoi2015]超能粒子炮·改 [lucas定理]
    3167: [Heoi2013]Sao [树形DP]
    bzoj 3812: 主旋律 [容斥原理 状压DP]
    有标号的二分图计数 [生成函数 多项式]
    有标号DAG计数 [容斥原理 子集反演 组合数学 fft]
    BZOJ 3028: 食物 [生成函数 隔板法 | 广义二项式定理]
  • 原文地址:https://www.cnblogs.com/zoneofmine/p/15221764.html
Copyright © 2011-2022 走看看