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:
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
链接地址: http://www.djcxy.com/p/78214.html
上一篇: C ++ 11多线程锁和原子基元
下一篇: C ++ 11具有原子属性的结构定义