Access to uninitialized atomic private variable in C ++

Suppose I have the following class:

class A { public: ... ... void incrementN() {++n_;} uint64_t getN() {return n_;} private: std::atomic<uint64_t> n_; ... ... }; 

Suppose that I initialize all other variables in the class except n_ , and that this is not a streaming local storage, so zero initialization is missing.

I create an object of class A and keep calling incrementN() .

If at some point I want the value n_ and I call getN() , can this cause the load() procedure to fail for atomic n_ ?

+5
source share
2 answers

The load uses memory_order_seq_cst by default. See here: http://en.cppreference.com/w/cpp/atomic/memory_order .

As mentioned in the comments, it should not give you any problems that normal ints will not give. Are you concerned about overflow if the uninitialized initial value is large? See here for possible consequences: https://www.owasp.org/index.php/Integer_overflow

0
source

The variable n_ member is simply not initialized. Accessing the field will result in a read in memory, and there is no reason for failure, although the location of these 8 bytes of memory is unknown.

The fact that the term is atomic does not matter here. This will cause the compiler not to use any optimization for this particular variable, and may also cause the cache line to be turned off in RAM with every write.

0
source

Source: https://habr.com/ru/post/1208112/


All Articles