[英]Visual C++ initialization inconsistence with gcc and clang
The following piece of code prints 0
compiled with vc++ and prints 1
compiled with g++ or clang++ : 下面的代码打印
0
用vc ++ 编译并打印1
用g ++或clang ++编译 :
#include <iostream>
#include <vector>
struct S
{
S() = default;
std::vector<int> v{0};
};
int main()
{
std::vector<S> s{{}};
std::cout << s.front().v.size() << std::endl;
}
Is it a bug in vc++ ? 这是vc ++中的错误吗?
If a user-defined constructor is provided ( S() {};
instead of S() = default;
) vc++ starts to print 1
, too . 如果提供了用户定义的构造函数(
S() {};
而不是S() = default;
) vc ++也开始打印1
。
In reading the Standard (C++11 n3485), 12.6.2/9
states that: 在阅读标准(C ++ 11 n3485)时,
12.6.2/9
指出:
If a given non-static data member has both a
brace-or-equal-initializer
and amem-initializer
, the initialization specified by themem-initializer
is performed, and the non-static data member'sbrace-or-equal-initializer
is ignored.如果给定的非静态数据成员同时具有
brace-or-equal-initializer
和mem-initializer
,则执行mem-initializer
指定mem-initializer
,并且非静态数据成员的brace-or-equal-initializer
值为忽略。
So the question becomes if the default
, ie the implicitly defined constructor contains a mem-initializer
or not. 所以问题就变成了
default
,即隐式定义的构造函数是否包含mem-initializer
。
Section 12.1/6
states: 第
12.1/6
节规定:
The implicitly-defined default constructor performs the set of initializations of the class that would be performed by a user-written default constructor for that class with no
ctor-initializer
(12.6.2) and an emptycompound-statement
.隐式定义的默认构造函数执行该类的初始化集,该初始化集将由该用户编写的默认构造函数执行,该类没有
ctor-initializer
(12.6.2)和空compound-statement
。
This would mean the implicitly generated (default) constructor has no mem-initializer
s and should indeed use the in-class initializer (the brace-or-equal-initializer
in the above quote). 这意味着隐式生成的(默认)构造函数没有
mem-initializer
并且确实应该使用类内初始化程序(上面引用中的brace-or-equal-initializer
)。
MSVC is wrong here (no surprise there, really). MSVC在这里是错误的(真的没有惊喜)。
This is not an answer but a comment requiring code. 这不是答案,而是需要代码的评论。
The following illustrates the compiler differences more clearly, I think: 下面更清楚地说明了编译器的差异,我认为:
#include <iostream>
#include <vector>
struct S
{
S() = default;
std::vector<int> v = std::vector<int>(13);
};
int main()
{
std::vector<S> s{{}};
std::cout << s.front().v.size() << std::endl;
}
Here g++ MinGW 5.1.0 reports 13 items, while MSVC 2015 update 2 reports 0 items. 这里g ++ MinGW 5.1.0报告13项,而MSVC 2015更新2报告0项。
Ie g++ uses the initializer specified in the class, while MSVC uses the one specified in the declaration of s
. 即g ++使用类中指定的初始化程序,而MSVC使用
s
声明中指定的初始化程序。 To me that looks like a problem with g++. 对我来说,这看起来像g ++的问题。 But I'm not sure: the only sure thing is that both can't be right.
但我不确定:唯一确定的是两者都不对。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.