• Effective C++ 笔记 —— Item 26: Postpone variable definitions as long as possible.


    This suggests the real meaning of "as long as possible" in this Item’s title. Not only should you postpone a variable's definition until right before you have to use the variable, you should also try to postpone the definition until you have initialization arguments for it. By doing so, you avoid constructing and destructing unneeded objects, and you avoid unnecessary default constructions. Further, you help document the purpose of variables by initializing them in contexts in which their meaning is clear.

    // finally, the best way to define and initialize encrypted
    std::string encryptPassword(const std::string& password)
    {
        using namespace std;
        if (password.length() < MinimumPasswordLength) // import std and check length
        {
            throw logic_error("Password is too short");
        }
        
        string encrypted(password); // define and initialize via copy constructor
        encrypt(encrypted);
        return encrypted;
    }

    "But what about loops?" you may wonder. If a variable is used only inside a loop, is it better to define it outside the loop and make an assignment to it on each loop iteration, or is it be better to define the variable inside the loop? That is, which of these general structures is better?

    // Approach A: define outside loop 
    Widget w;
    for (int i = 0; i < n; ++i) 
    {
        // w = some value dependent on i; 
        // ...
    }
    
    
    // Approach B: define inside loop
    for (int i = 0; i < n; ++i) 
    {
        // Widget w(some value dependent on i);
        // ...
    }

    In terms of Widget operations, the costs of these two approaches are as follows:

    • Approach A: 1 constructor + 1 destructor + n assignments.
    • Approach B: n constructors + n destructors.

    For classes where an assignment costs less than a constructordestructor pair, Approach A is generally more efficient. This is especially the case as n gets large. Otherwise, Approach B is probably better. Furthermore, Approach A makes the name w visible in a larger scope (the one containing the loop) than Approach B, something that’s contrary to program comprehensibility and maintainability. As a result, unless you know that (1) assignment is less expensive than a constructor-destructor pair and (2) you’re dealing with a performance-sensitive part of your code, you should default to using Approach B.

    Things to Remember:

    • Postpone variable definitions as long as possible. It increases program clarity and improves program efficiency.
  • 相关阅读:
    c++ 队列
    17:特殊类成员:函数指针5
    c++ deque 双端队列
    18:字符串-char型字符串
    c++ 16 this 和 继承 及继承机制中的构造函数 与 析构函数
    c++ string char* const char*
    c++ 小片段
    google protobuf 使用示例
    hibernate-cache
    hibernate-criteria查询(二)
  • 原文地址:https://www.cnblogs.com/zoneofmine/p/15247810.html
Copyright © 2020-2023  润新知