[英]std::vector of class containing atomic
I'm trying to create a vector containing instances of a class which, in turn, contains (among other things) std::atomic. 我正在尝试创建一个包含类实例的向量,该类继而包含(除其他外)std :: atomic。
I've tried the several: 我尝试了几种:
If a copy constructor is specified, I've tried two things: 如果指定了副本构造函数,我将尝试两件事:
with foo(foo& other) it will complain that no copy constructor was found for foo. 与foo(foo&other)一起,它将抱怨找不到foo的副本构造函数。
Edit: the copy constructor is foo(foo& other) : atomic(other.atomic.load()) {} 编辑:副本构造函数是foo(foo&other):atomic(other.atomic.load()){}
with foo(const foo& other) it will complain that there is no const copy constructor for std::atomic. 与foo(const foo&other)一起使用时,它将抱怨std :: atomic没有const复制构造函数。
Edit: the copy constructor is foo(const foo& other) : atomic(other.atomic.load()) {} 编辑:副本构造函数是foo(const foo&other):atomic(other.atomic.load()){}
I have absolutely no clue on how to fix this, so any help is much appreciated 我完全不知道如何解决此问题,因此非常感谢您的帮助
std::atomic
is neither copyable nor movable, by design. 根据设计,
std::atomic
既不可复制也不可移动。 Operations on std::vector
which cause it to reallocate require its elements to be at least movable. 导致
std::vector
重新分配的操作要求其元素至少是可移动的。 So, you have the following options: 因此,您有以下选择:
std::atomic
in the element class. std::atomic
。 Perhaps a std::unique_ptr<std::atomic>
could be used instead. std::unique_ptr<std::atomic>
代替。 std::unique_ptr<ElementClass>
instead (as suggested by @Richard Critten in comments). std::unique_ptr<ElementClass>
(如@Richard Critten在评论中所建议)。 std::atomic
. std::atomic
的不可移动性。 Give your class dummy copy/move operations to satisfy the compiler. 给您的类虚拟复制/移动操作,以使编译器满意。 Then, pre-allocate space in vector using
reserve
, and then only use functions which append elements (up to the preallocated size), access them, or delete from the end; 然后,使用
reserve
预先在vector中分配空间,然后仅使用附加元素(最大为预先分配的大小),访问它们或从末尾删除的函数; no in-the-middle insertions or deletions. 没有中间插入或删除。 This way, the dummy operations will never actually be called.
这样,虚拟操作将不会真正被调用。
Given the fragility of this approach, I would suggest two precautions: 考虑到这种方法的脆弱性,我建议采取两种预防措施:
std::vector
directly, but wrap it in your own NonResizableVector<T>
with a suitably restricted interface, and document it heavily. std::vector
,而是将其包装在具有适当限制的接口的自己的NonResizableVector<T>
,并对其进行大量记录。 Which one of these you should (or even can) use depends on what your class actually does. 您应该(甚至可以使用)其中哪一个取决于您的类实际执行的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.