简体   繁体   中英

why can't implicitly convert to a std::variant with std::atomic_bool

I'm writing a factory to for my classes, but having trouble compiling

struct A {
    std::atomic_bool flag{}; // remove this, there would be no error
    A() = default;
};

struct B {};

using base = std::variant<A, B>;

base create() {
    return A();
}

I got the error:

error: could not convert 'A()' from 'A' to 'base{aka std::variant<A, B>}'
return A();

why is this happenning? and why would it work if I remove std::atomic_bool in A ?

Atomics do not support being copied. If you want to copy them, you are in charge of deciding what the memory orders and the like of the read and write is.

Atomics are fundamentally identity based, not value based. They exist because you expect certain kinds of comtention on their identity.

constexpr atomic() noexcept(std::is_nothrow_default_constructible_v<T>);
constexpr atomic( T desired ) noexcept;
atomic( const atomic& ) = delete;

Generally a struct being copied around with an atomic in it is code smell. You may have a design flaw.

If not, you need to define what the copy means yourself. I am unaware of an obviously correct choice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM