The problem you are facing includes an as-if rule , which allows the optimizer to somehow convert your code if this does not affect the observed behavior of the program.
So, if you only write to a variable, but never use it in your program, the optimizer considers that there is no observable behavior, and assumes that it can effectively optimize the work on the record.
In your case, the data is observed outside of your program, and the way to tell this to the compiler and optimizer is through volatile ., Cppreference tells us (emphasis is my going forwrd):
an object whose type is unstable, or a subobject, a mutable object, or a mutable subobject of an object with a stable change. Each access (read or write operation, call of a member function, etc.) to a volatile object is considered as a visible side effect for the purpose of optimization [...]
For reference, the as-if rule is discussed in the draft C ++ standard in section 1.9 , which states:
[...] Rather, appropriate implementations are needed to emulate the (only) observed behavior of an abstract machine, as described below.
and with regard to the as-if volatile rule is also discussed in section 1.9 , and he says:
Access to unstable objects is evaluated strictly in accordance with the rules of an abstract machine.
source share