Uniform initialization of an atomic struct?
Asked Answered
R

2

8
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?

Rotenone answered 22/7, 2014 at 15:11 Comment(1)
I don't see any hack; one cannot even later manually assign an S to that beast. But let's think positive - it is not "just" by the standard but manifestly thread-safe that way... ;)Nevels
D
5

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});
Demarcate answered 22/7, 2014 at 17:13 Comment(0)
A
0

std::atomic<S> asd({1, 2});

std::atomic<S> has a constructor which takes a value of type S. The initializer list {1, 2} is implicitly converted to a temporary S because of this constructor.

Avoidance answered 22/7, 2014 at 15:25 Comment(5)
@Avoidance Can you explain why the uniform initialization doesn't work? It should work in my opinion.Skat
this doesn't compile on clang++ either. Both versions however compile on g++Skat
@Skat Ya, that's the issue I'm having... using clang. Is there a workaround?Rotenone
Yes, apparently I was wrong and your first version should also compile. My version works for me in MSVC 2013, however the first one doesn't. It's probably a bug in the compiler. As a workaround try std::atomic<S> asd(S{1,2});. What version of clang are you using, by the way?Avoidance
@axnsan: The symptom remains, however you twist it; there plainly is (/usr/include/c++/v1/atomic:632:58: error:) no viable conversion from 'S' to '_Atomic(S)'Nevels

© 2022 - 2024 — McMap. All rights reserved.