简体   繁体   中英

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.

I've tried the several:

  • if no copy constructor is specified, the compiler will give an error about the constructor being deleted.

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:

  • Stop storing std::atomic in the element class. Perhaps a std::unique_ptr<std::atomic> could be used instead.
  • Stop storing the element class directly in the vector, store std::unique_ptr<ElementClass> instead (as suggested by @Richard Critten in comments).
  • Write a copy or move constructor and assignment operator for your class, which will somehow work around the non-movability of 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:

    1. Make the dummies throwing, so that you catch any violations of the "no resizing" requirement ASAP.
    2. Do not use 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM