Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uniform initialization of an atomic struct?

struct S
{
    int x;
    int y;
};

std::atomic<S> asd{{1, 2}}; // what should this be? This doesn't work

Edit: Both {{1, 2}} and ({1, 2}) work in g++, neither work in clang. Is there a workaround for clang?

like image 550
David Avatar asked Jul 22 '14 15:07

David


People also ask

What is uniform initialization?

Uniform Initialization in C++ The uniform initialization is a feature that permits the usage of a consistent syntax to initialize variables and objects which are ranging from primitive type to aggregates. In other words, it introduces brace-initialization that applies braces ({}) to enclose initializer values.

Is struct initialized to 0?

If a structure variable has static storage, its members are implicitly initialized to zero of the appropriate type. If a structure variable has automatic storage, its members have no default initialization.

What is direct initialization in C++?

Direct initialization applies when initializing objects without explicit assignment. It also is also used for explicit casts, whether function-style or via static_cast and applies to Lambda closure arguments captured by value (which may be regarded as a special case of member initialization).

What is an initializer list in C++?

The initializer list is used to directly initialize data members of a class. An initializer list starts after the constructor name and its parameters.


1 Answers

This is clang bug 18097. Here's a long thread discussing the issue, which seems to be that clang only supports scalar types for T in atomic<T>. The C++11 standard clearly states (§29.5/1) that T can be any trivially copyable type.

Both the usages shown in the question should match this constructor

constexpr atomic(T) noexcept;

The only way I can think of working around this is to default construct atomic<S> and then use atomic::store to initialize the object.

std::atomic<S> asd;
asd.store({1,2});
like image 119
Praetorian Avatar answered Sep 22 '22 06:09

Praetorian