gpt4 book ai didi

c++ - 浮点成员是否保证使用 {} 语法初始化为零?

转载 作者:行者123 更新时间:2023-12-04 12:13:54 25 4
gpt4 key购买 nike

在 C++17 中,考虑以下情况 S是一个带有删除的默认构造函数和一个 float 成员的结构,当 S 用空大括号初始化时,标准是否保证 float 成员为零初始化?

struct A {
int x{};
};

struct S
{
S() = delete;

A a;
float b;
};

int main()
{
auto s = S{}; // Is s.b guaranteed to be zero?
}
在我看来,cppreference.com 不清楚,都说:

If the number of initializer clauses is less than the number of members and basesor initializer list is completely empty, the remaining members and bases (since C++17) are initialized by their default member initializers, if provided in the class definition, and otherwise (since C++14) copy-initialized from empty lists, in accordance with the usual list-initialization rules (which performs value-initialization for non-class types and non-aggregate classes with default constructors, and aggregate initialization for aggregates). If a member of a reference type is one of these remaining members, the program is ill-formed.


( from here ),这意味着 b 保证为零

In all cases, if the empty pair of braces {} is used and T is an aggregate type, aggregate-initialization is performed instead of value-initialization.


( from here )
这意味着 b 不能保证为零。
还有一个讨论似乎暗示虽然不能保证,但所有已知的编译器无论如何都会零初始化:

The standard specifies that zero-initialization is not performed when the class has a user-provided or deleted default constructor, even if that default constructor is not selected by overload resolution. All known compilers performs additional zero-initialization if a non-deleted defaulted default constructor is selected.


相关 Why does aggregate initialization not work anymore since C++20 if a constructor is explicitly defaulted or deleted?

最佳答案

这是 C++ 的一个怪癖,即 fixed in C++20 .同时您可以添加 explicit到已删除的默认构造函数以强制结构变为非聚合,并使您的代码成为有保证的编译错误:

struct A {
int x{};
};

struct S
{
explicit S() = delete;

const A a;
const float b;
};

int main()
{
auto s = S{}; // error: call to deleted constructor of 'S'
}

关于c++ - 浮点成员是否保证使用 {} 语法初始化为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69613009/

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