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;

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM