c++ - 成员初始化列表真的更有效吗?

标签 c++ performance constructor assignment-operator member-initialization

我同意这样的共识,即通常最好在成员初始化列表而不是构造函数的主体中初始化 C++ 数据成员,但我对 this explanation 持怀疑态度。

The other (inefficient) way to build constructors is via assignment, such as: Fred::Fred() { x_ = whatever; }. In this case the expression whatever causes a separate, temporary object to be created, and this temporary object is passed into the x_ object’s assignment operator. Then that temporary object is destructed at the ;. That’s inefficient.

这真的是正确的吗?我本以为编译器会省略默认构造的临时对象,该对象会立即被主体中的赋值替换。我不知道为什么我会这样想,但在阅读了上述声明后,我想我多年来一直在默默地假设它。

成员初始化列表实际上更有效吗?如果有,是不是这个原因?

最佳答案

Alexandrescu & Sutter的话来说(第 9 项)不要过早悲观

Avoiding premature optimization does not imply gratuitously hurting efficiency. By premature pessimization we mean writing such gratuitous potential inefficiencies as:

• Defining pass-by-value parameters when pass-by-reference is appropriate. (See Item25.)

• Using postfix + + when the prefix version is just as good. (See Item 28.)

• Using assignment inside constructors instead of the initializer list. (See Item 48.)

每当您在构造函数中编写赋值时,您的代码审阅者都会保持警惕:发生了什么特别的事情吗?他真的想要一些特殊的两阶段初始化吗(因为无论如何都有一个正在生成的成员的隐式默认构造!)。不要无缘无故地让代码的读者感到惊讶。

请注意,Alexandrescu 和 Sutter 在第 48 项中继续讨论潜在效率低下,但不要在任何地方声称在实际优化代码中存在实际效率低下。这也是无关紧要的,它是关于表达意图和避免效率低下的风险

关于c++ - 成员初始化列表真的更有效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42260463/

相关文章:

c++ - shared_ptr : horrible speed

c++ - 用不同的对象实例化 C++ Vector

c++ - 像 C::C(const C&&) 这样的构造函数我们怎么调用它?除了禁止从 const 移动外,还有其他用途吗?

c++ - 重载 `To to = from;` 和 `To to = {from};` 中的转换构造函数和转换运算符

c++ - cmake错误: "cc: error: unrecognized command line option ‘-std=c++20’ ; did you mean ‘-std=c++2a’ ?“

objective-c - 缓慢的 Swift 数组和字符串性能

c++ - 如何使用输入流重载将项目插入类中的映射成员?

java - 在jsp里面写java有性能差异吗?

c++ - 模拟整个图书馆

c++ - 如何检查两个数字是否在浮点类型精度限制的 "x"有效数字范围内?