C++11 现在支持在声明时设置类成员字段的值,如下所示:
class MyClass
{
private
int test = 0;
}
如果我也像这样在构造函数中初始化变量:
class MyClass
{
private
int test = 0;
public:
MyClass() : test(1)
{
}
}
这会导致变量的值设置两次,还是规范规定编译器应该优化它以仅初始化变量一次?如果规范没有规定任何内容,您是否知道著名编译器(例如 MSVC、GCC 等)在这方面的行为?
最佳答案
标准在 §12.6.2/9 中实际上对此有一条规则:
If a given non-static data member has both a brace-or-equal-initializer and a mem-initializer, the initialization specified by the mem-initializer is performed, and the non-static data member’s brace-or-equal-initializer is ignored. [ Example: Given
struct A { int i = /∗ some integer expression with side effects ∗/ ; A(int arg) : i(arg) { } // ... };
the A(int) constructor will simply initialize i to the value of arg, and the side effects in i’s brace-or-equal- initializer will not take place. — end example ]
因此在您描述的情况下,如果调用默认构造函数,只会执行那里定义的初始化,并且 test
将为 1
。
关于c++ - C++11 是否重新初始化已初始化的成员字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19877218/