条款26:尽可能延后变量定义式的出现时间
2010-03-05 17:49
267 查看
原代码:
修改后:避免构造和析构无用对象,而且还可以避免不必要的缺省构造。
下面这两个大致的结构中哪个更好一些?
对于 Widget 的操作而言,两个方法的成本:
方法 A:1 个构造函数 + 1 个析构函数 + n 个赋值。
方法 B:n 个构造函数 + n 个析构函数。
对于那些赋值的成本低于一个构造函数+析构函数对的成本的类,方法 A 通常更高效。特别是在 n 变得很大的情况下。否则,方法 B 可能更好一些。因此,除非你确信以下两点:(1)赋值比构造函数 /析构函数对成本更低,而且(2)你正在涉及你的代码中的性能敏感的部分,否则,你应该默认使用方法 B。
std::string encryptPassword(const std::string& password) { using namespace std; string encrypted;//声明过早,如果下面抛出异常,此声明增加负担 if (password.length() < MinimumPasswordLength) { throw logic_error("Password is too short"); } ... // do whatever is necessary to place an encrypted version of password in encrypted return encrypted; }
修改后:避免构造和析构无用对象,而且还可以避免不必要的缺省构造。
std::string encryptPassword(const std::string& password) { ... // check length std::string encrypted(password); // define and initialize via copy constructor encrypt(encrypted); return encrypted; }
下面这两个大致的结构中哪个更好一些?
// 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); ... ... }
对于 Widget 的操作而言,两个方法的成本:
方法 A:1 个构造函数 + 1 个析构函数 + n 个赋值。
方法 B:n 个构造函数 + n 个析构函数。
对于那些赋值的成本低于一个构造函数+析构函数对的成本的类,方法 A 通常更高效。特别是在 n 变得很大的情况下。否则,方法 B 可能更好一些。因此,除非你确信以下两点:(1)赋值比构造函数 /析构函数对成本更低,而且(2)你正在涉及你的代码中的性能敏感的部分,否则,你应该默认使用方法 B。
相关文章推荐
- 《Effective C++》之条款26:尽可能延后变量定义式的出现时间
- Effective C++条款26解读: 尽可能延后变量定义式的出现时间
- effective C++ 条款 26:尽可能延后变量定义式的出现时间
- 条款26:尽可能延后变量定义式的出现时间
- 条款26:尽可能延后变量定义式的出现时间(Postpone variable definitions as long as possible)
- 《Effect C++》学习------条款26:尽可能延后变量定义式的出现时间
- 条款26:尽可能延后变量定义式的出现时间
- 【Effection C++】读书笔记 条款26:尽可能延后变量定义式的出现时间
- Effective C++ 条款26 尽可能延后变量定义式的出现时间
- Effective C++ -----条款26:尽可能延后变量定义式的出现时间
- Effective C++ 条款26:尽可能延后变量定义式的出现时间
- Effective C++:条款26:尽可能延后变量定义式的出现时间
- 条款26 尽可能延后变量定义式的出现时间
- 条款26:尽可能延后变量定义式出现的时间
- 条款26:尽可能延后变量定义式的出现时间
- 《Effective C++》学习笔记条款26 尽可能延后变量定义式的出现时间
- 条款26:尽可能延后变量定义式的出现时间
- Effective C++:条款26:尽可能延后变量定义式的出现时间
- 尽可能延后变量定义式的出现时间(Effective_C++(26))
- 条款26 尽可能延后变量定义出现的时间