Arrays 使用原子数组初始化类或结构

Arrays 使用原子数组初始化类或结构,arrays,c++11,atomic,copy-constructor,initializer-list,Arrays,C++11,Atomic,Copy Constructor,Initializer List,如何使用原子变量数组编写类/结构的用户定义副本构造函数?例如,下面的代码不编译 struct foo { std::array<std::atomic_int,3> a; foo() = default; foo(const int& i, const int& j, const int& k):a{{i,j,k}}{} } structfoo { std::数组a; foo()=默认值; foo(constin

如何使用原子变量数组编写类/结构的用户定义副本构造函数?例如,下面的代码不编译

struct foo
{    
     std::array<std::atomic_int,3> a;
     foo() = default;
     foo(const int& i, const int& j, const int& k):a{{i,j,k}}{}
}
structfoo
{    
std::数组a;
foo()=默认值;
foo(constint&i,constint&j,constint&k):a{{i,j,k}{}
}
原因是“错误:在此处声明_原子_基(常量_原子_基&)=delete”;即在原子类型的定义中删除了该错误。如果它是非原子的,它就已经完成了

有没有办法做到这一点


我已经完成了这里的讨论

只需手动定义复制构造函数,并在构造函数体中逐个元素复制数组元素(如果应该复制的话)。请注意,这不是原子的。

将删除
std::atomic
copy构造函数,因为无法以原子方式将值从一个对象复制到另一个对象:

std::atomic<int> a, b;
a = b; //  use of deleted function 'std::atomic<int>& std::atomic<int>::operator=(const std::atomic<int>&)'

嗨@SebastianRedl,我试过了,但它不起作用,原因正是你刚才提到的警告。我的目的是为这个类编写一个构造函数,但是即使a不是数组,它也不起作用。注意:
foo(const int&i,const int&j,const int&k)
不是一个复制构造函数。如果你想编写这个构造函数,你需要更多的大括号(这通常很有帮助)
foo(const int&i,const int&j,const int&k):a{{{i},{j},{k}}{}{/code>,这与聚合初始化有关,它调用聚合成员的副本初始化。这个问题现在作为foo(const int&i,const int&j,const int&k){a[0]。store(int(i));a[1]。store(int(j));a[2]。store(int(k));}来解决。谢谢@dyp对于一般情况来说是个好主意,但是它会使
变换的lambda有点奇怪。我不会编写
std::transform(begin(b),end(b),begin(a),[](decltype(*b.cbegin())I){return I.load();})
,除非泛型是绝对关键的,尽管我可能会在我编写的代码的副本构造函数中使用
[](decltype(other.a[0])I){return I.load();}
,但这不是一个如此答案<代码>[](const auto&foo){return foo.load()}
当然很好-我假设OP没有C++14编译器;)@dyp tsk,tsk-复制!对不起,我的编辑踩到你了。:D好的。。。我第二次感到困惑嗨,伙计们,凯西和@dyp,谢谢你们的回答,谢谢你们的讨论。我的目的是将用户定义的复制构造函数编写为foo(const int&i,const int&j,const int&k),实际上从您的讨论中得到了线索,我现在将其命名为foo(const int&i,const int&j,const int&k){a[0]。store(int(i));a[1]。store(int(j));a[2]。store(int(k));},它工作得非常好。我不能推翻你的答案,因为我没有那么多的声誉,因为它闪烁,但,我确实想这样做。dyp请投票支持这一讨论。
std::atomic<int> a, b;
a = b.load();
std::array<std::atomic<int>, 3> a, b;
for (const auto& i : b) {
  a = i.load();
}
std::array<std::atomic<int>, 3> a, b;
std::transform(begin(b), end(b), begin(a),
               [](int i){return i;});
foo(const foo& other) {
    std::transform(begin(other.a), end(other.a), begin(a),
                   [](int i){return i;});
}