I understand that atomic has a copy constructor that's deleted, but what can I do to make this code work? How can I possibly define a copy constructor inside vector for atomic?
#include <atomic>
#include <vector>
int main() {
std::vector<std::atomic<int>> examp;
examp.resize(64);
}
You can't have a vector of std::atomic<int> because it is not copyable or movable, but you can have a vector of unique_ptrs to atomic<int>. If you really need a run-time variable-size vector of atomics, this may be a viable alternative. Here is an example:
#include <iostream>
#include <atomic>
#include <vector>
#include <memory>
using namespace std;
int main() {
std::vector<std::unique_ptr<std::atomic<int>>> examp;
examp.resize(64); // 64 default unique_ptrs; they point to nothing
// init the vector with unique_ptrs that actually point to atomics
for (auto& p : examp) {
p = std::make_unique<std::atomic<int>>(0); // init atomic ints to 0
}
// use it
*examp[3] = 5;
for (auto& p : examp) {
cout << *p << ' ';
}
cout << '\n';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With