代码之家  ›  专栏  ›  技术社区  ›  ar2015

如何分配原子类型的向量?

  •  4
  • ar2015  · 技术社区  · 5 年前

    如何分配原子类型的向量成员?

    #include <iostream>
    #include <thread>
    #include <vector>
    
    using namespace std;
    
    int main()
    {
        vector<atomic<bool>> myvector;
        int N=8;
        myvector.assign(N,false);
        cout<<"done!"<<endl;
    }
    

    https://wandbox.org/permlink/lchfOvqyL3YKNivk

    prog.cc: In function 'int main()':
    prog.cc:11:28: error: no matching function for call to 'std::vector<std::atomic<bool> >::assign(int&, bool)'
       11 |     myvector.assign(N,false);
          |                            ^
    
    1 回复  |  直到 5 年前
        1
  •  6
  •   O'Neil    5 年前

    std::atomic 既不可复制也不可移动构造,因此您可以改为:

    std::vector<std::atomic<bool>> myvector(8);
    for (auto& b : myvector) { std::atomic_init(&b, false); }