atomic vector的使用

原始需求:使用stl容器装载atomic

#include <atomic> #include <vector> int main(void) { std::vector<std::atomic<int>> v_a; std::atomic<int> a_i(1); v_a.push_back(a_i); return 0; }

上述代码编译即报错,因为atomic<T>缺少拷贝构造函数和拷贝赋值函数。

解决方案:
1.使用vector

#include <atomic>
#include <vector>

template <typename T>
struct atomwrapper
{
  std::atomic<T> _a;

  atomwrapper()
    :_a()
  {}

  atomwrapper(const std::atomic<T> &a)
    :_a(a.load())
  {}

  atomwrapper(const atomwrapper &other)
    :_a(other._a.load())
  {}

  atomwrapper &operator=(const atomwrapper &other)
  {
    _a.store(other._a.load());
  }
};

int main(void)
{
  std::vector<atomwrapper<int>> v_a;
  std::atomic<int> a_i(1);
  v_a.push_back(a_i);
  return 0;
}
2.使用deque
std::deque<std::atomic<int>> d;

d.emplace_back(1);
d.emplace_back(2);
d.pop_back();
 
posted @ 2021-07-02 16:47  angryCoder996  阅读(2137)  评论(0编辑  收藏  举报