c++ - MyType 允许 std::atomic<MyType> 的确切要求是什么?

标签 c++ c++11 stdatomic

我想在线程之间传递一些信息。 原子听起来像是要使用的东西。 我看了一下this 。并发现一个简单的结构,例如

struct MyType{
  int val_a,val_b;
  float vals_c[5];
};

应该填写断言:

static_assert( 
  std::is_trivially_copyable<MyType>::value &&
  std::is_copy_constructible<MyType>::value &&
  std::is_move_constructible<MyType>::value &&
  std::is_copy_assignable<MyType>::value &&
  std::is_move_assignable<MyType>::value, 
  "MyType is not suitable for std::atomic");

)

但是一个简单的程序

//... MyType and static_assert

int main(int argc,char *argv[]){
   MyType a;
   std::atomic<MyType> b;
   b = a;
   a = b;
   return 0;
}

编译失败:

undefined reference to `__atomic_store'
undefined reference to `__atomic_load'

我在 64 位 ubuntu 16.04 上使用 gcc 版本 5.4。

使用的标志是:-pipe -g -std=gnu++11 -Wall -W -fPIC

这是对 std::atomic 的完全错误使用吗? MyType 有什么要求?或者只是这个设置中缺少一些东西?

最佳答案

一如既往,documentation是你的 friend 吗:

The primary std::atomic template may be instantiated with any TriviallyCopyable type T satisfying both CopyConstructible and CopyAssignable. The program is ill-formed if any of following values is false:

std::is_trivially_copyable<T>::value
std::is_copy_constructible<T>::value
std::is_move_constructible<T>::value
std::is_copy_assignable<T>::value
std::is_move_assignable<T>::value

所以,你的断言是好的。

后来它说:

On gcc and clang, some of the functionality described here requires linking against -latomic.

因此,如果程序仍然无法构建,you may need to link against libatomic .

如果它仍然不起作用,则可能存在编译器错误。

关于c++ - MyType 允许 std::atomic<MyType> 的确切要求是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59751795/

相关文章:

c++ - const char* 在构造函数中的用法

c++ - 我们可以用 C++ 开关写这个吗?

c++ - 保证元素位置固定的容器

c++ - 使用 for_each 或 accumulate 来计算频率

c++ - 赋值是否等同于 std::atomic<bool> 的加载/存储

c++ - 将代码从 unix 移动到 windows xp

c++ - 通过引用传递是作为指针传递的特例吗?

c++ - 为什么不为将析构函数定义为 =default 的类合成移动操作?

c++ - 如何交换两个 std::atomic 变量?

c - 只有一个线程使用 memory_order_seq_cst 有用吗?