Should the trivial default constructor consider the default element initializer here?

Consider the code:

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

Note that although stru has a default element initializer, it still qualifies as a cumulative type with C ++ 14. std::atomic has a trivial default constructor. According to the standard, should as elements be initialized to zero? clang 6.0.0 does not do this (see here ), while gcc 7.2.0 seems like this (see here ).

+4
source share
2 answers

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

In the following definitions of operations:

  • a refers to one of the atomic types.

[...]

 A::A() noexcept = default; 

Effects: leaves the atomic object in an uninitialized state. [Note: these semantics provide compatibility with C. - end note]

as not initialized before loading. Thus, the usual undefined behavior should follow.

+3
source

According to cppreference, the constructor std::atomic::atomic() does not initialize the obj object:

 atomic() noexcept = default; 

1) The default constructor is trivial: initialization is not performed except for zero initialization of static and thread-local objects. std :: atomic_init can be used to complete initialization.

0
source

Source: https://habr.com/ru/post/1275991/


All Articles