我同意这样的共识,即通常最好在成员初始化列表而不是构造函数的主体中初始化 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/