Yash Chandarana Yash Chandarana - 8 months ago 44
C++ Question

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

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
will be atomic here(except for checking it with multiple threads)?

Answer Source

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.