gpt4 book ai didi

c++ - 琐碎的默认构造函数应该在这里尊重默认成员初始值设定项吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:37:44 25 4
gpt4 key购买 nike

考虑代码:

#include <atomic>
#include <iostream>

struct stru {
int a{};
int b{};
};

int main() {
std::atomic<stru> as;
auto s = as.load();
std::cout << s.a << ' ' << s.b << std::endl;
}

请注意,尽管 stru 具有默认成员初始值设定项,但自 C++14 起,它仍然有资格作为聚合类型。 std::atomic 有一个简单的默认构造函数。按照标准,as的成员是否应该初始化为零? clang 6.0.0 不这样做(参见 here ),而 gcc 7.2.0 似乎如此(参见 here )。

最佳答案

严格来说,我认为这两个编译器都是正确的,因为您的程序表现出未定义的行为。引用 n4140 (C++14),[atomics.types.operations.req] ,强调我的:

In the following operation definitions:

  • an A refers to one of the atomic types.

[...]

A::A() noexcept = default;

Effects: leaves the atomic object in an uninitialized state. [ Note: These semantics ensure compatibility with C. — end note ]

as 在加载之前未初始化。因此,必须遵循有关未定义行为的通常说法。

关于c++ - 琐碎的默认构造函数应该在这里尊重默认成员初始值设定项吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49387069/

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