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.