Search code examples
c++11structthread-safetyatomicdefinition

C++11 Struct definition with atomic attribute


In C++11 I have a struct with lots of attributes like so:

#include <atomic>
struct Foo {
  int x;
  int y;
  // ...
  // LOTS of primitive type attributes, followed by...
  // ...
  std::atomic_bool bar;
}

And I'd like to define an instance like so:

bool bar_value = true;
Foo my_foo = {/*attribute values*/, bar_value};

However, the atomic_bool is throwing a "use of deleted function" error because I think copy constructing is not allowed on atomics. Is there any way around this, short of writing out a constructor or assigning each value individually?

It just seems inconvenient to have to treat this otherwise relatively banal struct in a special way just because one of its many attributes is a special case.

Updates:

  • Any takers? I've been looking around, but there doesn't seem to be any straightforward way to resolve this.

Solution

  • Try wrapping the initialization of the atomic_bool in its own initializer list. It worked for me in g++ 4.7.

    #include <atomic>
    #include <iostream>
    
    struct Foo
    {
        int x;
        int y;
        std::atomic_bool bar;
    };
    
    int main(int, char**)
    {
        Foo f1 = {1, 2, {true}};
        Foo f2 = {3, 4, {false}};
    
        std::cout << "f1 - " << f1.x << " " << f1.y << " "
                  << (f1.bar.load()?"true":"false") << std::endl;
        std::cout << "f2 - " << f2.x << " " << f2.y << " "
                  << (f2.bar.load()?"true":"false") << std::endl;
    }
    

    I got the following output:

    $ g++ -std=c++11 test.cpp -o test && ./test
    f1 - 1 2 true
    f2 - 3 4 false