I'm trying to create a vector containing instances of a class which, in turn, contains (among other things) 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.
Edit: the copy constructor is 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.
Edit: the copy constructor is 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. Operations on std::vector
which cause it to reallocate require its elements to be at least movable. So, you have the following options:
std::atomic
in the element class. Perhaps a std::unique_ptr<std::atomic>
could be used instead. std::unique_ptr<ElementClass>
instead (as suggested by @Richard Critten in comments). 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; 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. Which one of these you should (or even can) use depends on what your class actually does.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.