默认成员初始化的最佳实践

huangapple go评论55阅读模式
英文:

Default member initialization best practice

问题

在以下代码中初始化成员变量是否有性能差异?我曾认为应该使用“第二”种方法,因为它将变量初始化为2,而“第一”种方法将首先初始化为默认值(默认为零),然后分配为1。但我发现“第一”种方法随处可见,甚至在Stack Overflow上也是如此。所以我想知道它们在C++20中是否不再有差异?

class example
{
private:
int first = 1;
int second { 2 };
}
英文:

Is there a performance difference in initializing the member variables in the following code? I used to think I should use the 'second' approach, as it initializes the variable to 2 while first will be initialzed to the default value (which will be zero) and then assigned to 1. But I am seeing the first approach everywhere, also at stackoverflow. So I wonder if they don't make a difference now in c++20?

class example
{
private:
int first = 1;
int second { 2 }
};

答案1

得分: 1

你特定情况下没有性能差异。然而,如果成员变量类型只定义了explicit构造函数,你可能无法使用=语法来初始化它的值。如果有可用的移动构造函数,你仍然可以执行T m_t = T{},但对于非平凡可移动类型,这可能会伴随一些额外的计算。此外,如果没有可用的移动构造函数,那将调用复制构造函数(如果可用),对于非平凡可复制类型,与移动构造函数相比,通常会对性能产生更大的影响。

英文:

There is no performance difference in you specific case. However, if the member variable type has only explicit constructors defined, you might not be able to use the = syntax to initialize it with a value. You might be still able to do T m_t = T{} if there is a move constructor available, but that could come with some additional computations for non-trivially-movable types. Moreover, if no move constructor is available, that would call the copy constructor (if it is available), and for non-trivially-copyable types that one has usually some bigger performance impact compared to the move one.

huangapple
  • 本文由 发表于 2023年3月7日 01:22:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75653921.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定