gpt4 book ai didi

c++ - Visual C++ 初始化与 gcc 和 clang 不一致

转载 作者:太空狗 更新时间:2023-10-29 20:54:33 24 4
gpt4 key购买 nike

下面这段代码prints 0 compiled with vc++prints 1 compiled with g++ or 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;
}

它是 vc++ 中的错误吗?

如果提供了用户定义的构造函数(S() {}; 而不是 S() = default;)vc++ starts to print 1, too .

最佳答案

在阅读标准 (C++11 n3485) 时,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.

所以问题就变成了 default,即隐式定义的构造函数是否包含 mem-initializer

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 empty compound-statement.

这意味着隐式生成的(默认)构造函数没有mem-initializer并且确实应该使用类内初始化器(brace-or-equal-initializer 在上面的引述中)。

MSVC 在这里是错误的(这并不奇怪,真的)。

关于c++ - Visual C++ 初始化与 gcc 和 clang 不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38762157/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com