c++ - C++11 是否重新初始化已初始化的成员字段?

标签 c++ c++11

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/

相关文章:

c++ - std::map 中键/值类型的复制/移动要求?

c++ - 如何实现避免未定义行为的侵入式链表?

c++ - 如何在linux数据类型中定义#define S64_MIN?

C++ 将自定义类型的转换运算符重载为 std::string

c++ - 在什么意义上 const 只允许对可变成员变量进行原子更改?

c++ - Catch2:检查结果是否为 0.0 且相对错误失败

c++ - OpenGL 使用 glNewList 和 glDrawElements

python - 如何编写一个函数来接受 SWIG 中的 Fraction 对象?

c++ - 使用从外部参数包中获取的参数类型声明一个函数

opencv - 尽管捕获了OpenCV VideoWriter,但仍在全盘上引发运行时错误