Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector(array) of atomic variables

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);
}
like image 713
J. Doe Avatar asked Nov 27 '25 05:11

J. Doe


1 Answers

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';
}
like image 72
Luis Guzman Avatar answered Nov 28 '25 19:11

Luis Guzman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!