普通的默认构造函数应该在这里尊重默认成员初始化程序吗? [英] Should trivial default constructor respect default member initializer here?

查看:128
本文介绍了普通的默认构造函数应该在这里尊重默认成员初始化程序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑代码:

#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不会执行此操作(请参见此处),而gcc 7.2.0则是如此(请参见此处).

Note that although stru has default member initializer, it still qualifies as an aggregate type since C++14. std::atomic has a trivial default constructor. According to the standard, should the members of as be initialized to zero? clang 6.0.0 doesn't do this (see here), while gcc 7.2.0 seems so (see here).

推荐答案

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

Strictly speaking, I think both compilers are right, in that your program exhibits undefined behavior. To quote n4140 (C++14), [atomics.types.operations.req], emphasis mine:

在以下操作定义中:

In the following operation definitions:

  • A表示一种原子类型.

[...]

A::A() noexcept = default;

效果:使原子对象处于未初始化状态. [注意:这些语义确保与C的兼容性.—尾注]

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

as在加载之前未初始化.因此,必须遵循有关未定义行为的常见俗语.

as is uninitialized before the load. So the usual spiel about undefined behavior must follow.

这篇关于普通的默认构造函数应该在这里尊重默认成员初始化程序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆