• 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动态代理详解
    (10) openssl dhparam(密钥交换)
    (9) openssl enc(对称加密)
    (8) openssl rsautl(签名/验证签名/加解密文件)和openssl pkeyutl(文件的非对称加密)
    (7) openssl dgst(生成和验证数字签名)
    (6) openssl passwd(生成加密的密码)
    (5) openssl speed(测试算法性能)和openssl rand(生成随机数)
    (4) openssl rsa/pkey(查看私钥、从私钥中提取公钥、查看公钥)
    (3) openssl genrsa(生成rsa私钥)
    (2) OpenSSL命令
  • 原文地址:https://www.cnblogs.com/zoneofmine/p/15221764.html
Copyright © 2020-2023  润新知