简体   繁体   中英

Resize a std::vector<std::atomic_bool> assigning true to all atomic bools

I have a std::vector<std::atomic_bool> that I want to resize to some arbitrary n , wherein all newly created objects are assigned a value of true. The program will not build because resize() relies on the copy constructor of the data type, not its assignment operator. Is there any way to assign a default value to an atomic_bool or would I be stuck with using a loop and store() ing all the values?

What I've tried:

#include <atomic>
#include <vector>

class foo() {
public:
    std::vector<std::atomic_bool> vec;

    foo() {
        std::atomic_bool temp(true);

        vec.resize(100, std::atomic_bool(true)); //try 1

        vec.resize(100, temp); //try 2
    }
}

If T is neither copyable nor movable, then std::vector<T> cannot be resized. Period. In this case, you might want to consider std::deque .

std::deque<std::atomic_bool> D;
D.emplace_back(true);  // write a helper to do this 100 times if you want

However, note that a standard library container of atomics is not atomic; adding new elements to the container is not an atomic operation so you will probably have to protect the container with a mutex, which might eliminate any benefits of storing atomics inside.

Brian's suggestion of a deque is sound and still allows O(1) random access, though I'd expect it to be a couple times slower than a vector . Kerrek's suggestion of a higher level class managing a vector 's also workable.

FWIW, another option is wrapping the individual std::atomic_bool s with a type that orchestrates copy construction as a combination of default construction and assignment:

struct Copy_Constructible_Atomic_Bool : std::atomic_bool
{
    Copy_Constructible_Atomic_Bool(const std::atomic_bool& rhs)
    {
        std::atomic_bool::operator=(rhs);
    }

    Copy_Constructible_Atomic_Bool(const Copy_Constructible_Atomic_Bool& rhs)
    {
        std::atomic_bool::operator=(rhs);
    }
};

Usage:

std::vector<Copy_Constructible_Atomic_Bool> vec;
std::atomic_bool temp;
temp = true;
vec.resize(100, temp);

atomics aren't designed to be moved, so you cant reallocate them to be somewhere else. However, you can replace them.

vec = std::vector<std::atomic_bool>(100, true);

(I'm not 100% certain you can use true here, but I believe you can.)

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