Initialisation of vector of atomics

You are correct to be worried. According to standard the atomics has the default constructor called, however they have not been initialized as such. This is because the default constructor doesn't initialize the atomic:

The default-initialized std::atomic<T> does not contain a T object, and its only valid uses are destruction and initialization by std::atomic_init

This is somewhat in violation of the normal language rules, and some implementations initialize anyway (as you have noted).

That being said, I would recommend taking the extra step to make 100% sure they are initialized correctly according to standard - after all you are dealing with concurrency where bugs can be extremely hard to track down.

There are many ways to dodge the issue, including using wrapper:

struct int_atomic {
   std::atomic<int> atomic_{0};//use 'initializing' constructor
};

Even if the default constructor were called (it isn't, because it's trivial) it doesn't really do anything.

Zero-initialisation obviously cannot be guaranteed to produce a valid atomic; this'll only work if by chance a valid atomic is created by zero-initialising all its members.

And, since atomics aren't copyable, you can't provide a initialisation value in the vector constructor.

You should now loop over the container and std::atomic_init each element. If you need to lock around this, that's fine because you're already synchronising the vector's creation for the same reason.

Tags:

C++

Vector

Atomic