Search code examples
c++c++11vectoratomicpointer-to-pointer

Is it correct to declare a dynamic array of atomic using double pointers in C++?


I need to create an array of atomic integers i.e. n integers each of which are atomic. I found that std::vector<std::atomic<int>> will not work but then I tried the following approach and it compiles successfully with clang.

int n;
std::cin >> n;
std::atomic<int> **a;
a = new std::atomic<int>* [n];
for(int i = 0; i < n; i++)
{
    a[i] = new std::atomic<int>();
}

I'm not sure if doing this is correct, is it? Also, is there any method to verify if all the a[i][0] will be atomic here(except for checking it with multiple threads)?


Solution

  • Your code is correct (except for resource leaks, I assume destroying the arrays has been omitted for brevity), but complicated. First of all, why do you use a "double pointer" or pointers to pointers? Why not this:

    std::atomic<int> * a1 = new std::atomic<int>[ n ];
    

    If this works for you, then

    std::vector<std::atomic<int>> a2( n );
    

    should work too, there are a few differences, but the most important one probably is that if you pass a1 by value, the contents are not copied, but if you pass in a2 by value, they are.

    This might be a problem for you, because std::atomic is not copyable. So you should always pass a2 by reference, except if you need to transfer ownership; in that case use std::move and rvalue references. You can't pass a2 by value.