简体   繁体   English

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

[英]Does C++11 re-initialize initialized member fields?

C++11 now supports setting the value of a class member field at declaration time, like this: C ++ 11现在支持在声明时设置类成员字段的值,如下所示:

class MyClass
{
private
  int test = 0;
}

If I also initialize the variable in the constructor like this: 如果我也在构造函数中初始化变量,如下所示:

class MyClass
{
private
  int test = 0;

public:
  MyClass() : test(1)
  {
  }
}

will this cause the variable to have its value set twice, or the specification dictates that the compiler should optimise this to initialize the variable only once? 这会导致变量的值设置两次,还是规范规定编译器应该优化它以仅将变量初始化一次? If the specification doesn't dictate anything, do you know the behaviour of the famous compilers (eg MSVC, GCC, etc.) with respect to this? 如果规范没有规定任何内容,您是否知道着名编译器(例如MSVC,GCC等)的行为?

The Standard actually has a rule for this, in §12.6.2/9: 标准实际上有一个规则,在§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. 如果给定的非静态数据成员同时具有大括号或等号初始化器和mem-initializer,则执行mem-initializer指定的初始化,并且非静态数据成员的大括号或等于初始值为忽略。 [ 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. A(int)构造函数将简单地将i初始化为arg的值,并且不会发生i的括号或等于初始值设定项中的副作用。 — end example ] - 结束例子]

So in the case you described, if the default constructor is called, only the initialization defined there will be performed, and test will be 1 . 因此,在您描述的情况下,如果调用默认构造函数,则仅执行在那里定义的初始化,并且test将为1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM