The risk of wrapper class usage for std::vector<std::atomic<T> >

Dear experts

I understand std::vector<std::atomic<T>> is prohibited,
but there is wrapper class of std::atomic<T> enables STL vector usage as the below.

https://stackoverflow.com/questions/13193484/how-to-declare-a-vector-of-atomic-in-c


I think that std::vector of wrapper class such as the below (std::vector<atomicwrapper<int> >) is safely used when JUST ELEMENT ACCESS is used. (elements are constructed in the previous )
each element is accessed by get() function as reference.

Is it correct?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <atomic>

template <typename T>
class atomicwrapper
{
private:
    std::atomic<T> _a;
public:

    std::atomic<T>& get(){return _a;}

    atomicwrapper()
            :_a()
    {}

    atomicwrapper(const std::atomic<T> &a)
            :_a(a.load())
    {}

    atomicwrapper(const T value)
            :_a(value)
    {}

    atomicwrapper(const atomicwrapper &other)
            :_a(other._a.load())
    {}

    atomicwrapper &operator=(const atomicwrapper &other)
    {
        _a.store(other._a.load());
    }
};


Kind regards
Last edited on
Is your question whether a vector of atomicwrappers would be thread-safe to, for example, resize in one thread and access in another? If so, the answer is obviously that it wouldn't be.
Dear helios

Thank you for your answer.

As you said, STL container operation such as resize is oobviously non thread safe.

Limitted to element access, is it thread safe? For example, get function of the above example. This just entails reference access before atomic operation.
Understanding "access" as reading and writing, yes.
Dear helios

Thank you for your kind reply.

Yes, I meant just reading and writing each element.
I can use the wrapper class with confidence for my purpose.

I appreciate your advice.

Kind regards
Topic archived. No new replies allowed.