Why atomic<T> Has No Constructors

In C++03 mode template class atomic<T> deliberately has no declared constructors, because examples like GetUniqueInteger, shown in the Atomic Operations section, are commonly required to work correctly even before all file-scope constructors have been called. If atomic<T> declared a constructor, a file-scope instance might be initialized after it had been referenced.

As for any C++ class with no declared constructors, an object X of type atomic<T> is automatically initialized to zero in the following contexts:

  • X is declared as a file-scope variable or as a static data member of a class.

  • x is a member of a class and explicitly listed in the constructor's initializer list.

The code below illustrates these points.

atomic<int> x;  // zero-initialized because it is at file scope
class Foo {
    atomic<int> y;
    atomic<int> notzeroed;
    static atomic<int> z;
    Foo() :
        y()     // zero-initializes y.
        // notzeroed has unspecified value here.
atomic<int> Foo::z; // zero-initialized because it is a static member

In C++11 mode, template class atomic<T> has two constructors :

  • atomic() = default; default constructor generated by compiler. This constructor behaves same as if there were no user defined constructors declared at all. This constructor keeps backward compatibility with C++03 mode, e.g. allow zero-initialization of global objects.

  • constexpr atomic(T arg); this constructor allows initialization of atomic variable during translation time, only if the argument is itself a translation time constant, otherwise initialization is performed at run time.

Per informazioni più dettagliate sulle ottimizzazioni basate su compilatore, vedere il nostro Avviso sull'ottimizzazione.