C++使用原子变量

1、C++给我们typedef了很多原子变量

  /// atomic_bool
  typedef atomic<bool>            atomic_bool;

  /// atomic_char
  typedef atomic<char>            atomic_char;

  /// atomic_schar
  typedef atomic<signed char>        atomic_schar;

  /// atomic_uchar
  typedef atomic<unsigned char>        atomic_uchar;

  /// atomic_short
  typedef atomic<short>            atomic_short;

  /// atomic_ushort
  typedef atomic<unsigned short>    atomic_ushort
....

可以直接拿来用

 2、查看atomic的类声明源码

 2.1、构造函数

atomic() noexcept = default;
~atomic() noexcept = default;
atomic(const atomic&) = delete;
atomic& operator=(const atomic&) = delete;
atomic& operator=(const atomic&) volatile = delete;

可以看出拷贝构造函数、赋值构造函数都是delete的,而整个类是模板类【其实是结构体】,所以要声明或者初始化应该这样:

①、头文件中

static std::atomic_bool a;

②、cpp中

std::atomic<bool> MainWindow::a(false);

这是通过类模板传入参数的形式进行初始化

如果是全局变量:

③、

std::atomic_int g_iCount = 100;



长风破浪会有时,直挂云帆济沧海!
可通过下方链接找到博主
https://www.cnblogs.com/judes/p/10875138.html
原文地址:https://www.cnblogs.com/judes/p/15031419.html