test eax, eax
How does it work in this case?
Objects declared as volatile are not used in certain optimizations because their values can change at any time. The system always reads the current value of a volatile object at the point it is requested, even if a previous instruction asked for a value from the same object. Also, the value of the object is written immediately on assignment.
Also, when optimizing, the compiler must maintain ordering among references to volatile objects as well as references to other global objects. In particular,
A write to a volatile object (volatile write) has Release semantics; a reference to a global or static object that occurs before a write to a volatile object in the instruction sequence will occur before that volatile write in the compiled binary.
A read of a volatile object (volatile read) has Acquire semantics; a reference to a global or static object that occurs after a read of volatile memory in the instruction sequence will occur after that volatile read in the compiled binary.
This allows volatile objects to be used for memory locks and releases in multithreaded applications.
> How is declaring a variable volatile different if the variable is a primitive type or a class object? I am guessing, declaring a class object volatile will make all of its members volatile
> If this is true, then is this rule strictly followed by the compilers?
Can't say for all C/C++ compilers out there, but ISO C/C++ compliant compilers should.
> Is there a need to declare a variable (integral or class
object)volatile whenaccess to it isprotected bysynchronization
objectsin multi-threaded environment?
object takes care of synchronization, that's why it is called synchronization object.