Q9: What does volatile mean in C++, precisely? No easily accessible online answer, so let’s not dwell too long.
A9.0 (one of the common short answers): this keyword tells compiler to remove all “optimizations on the variable”, but what are they exactly?
A9.1 (one of the common answers): it tells compiler to always hit hardware memory, rather than some Software cache. You can verify the assembly generated by compiler. Assembly should show CPU instructions of memory access every time rather than selectively.
Note — Upon executing the instruction, if CPU uses some sort of Hardware-based caching, compiler has no control no knowledge — Compiler did the right thing and volatile is honored.
A9.2: it means the memory location can be updated by hardware so compiler can’t “assume” this process’s threads are the only writers to that memory location. Without this assumption, compiler must always generate cpu instruction to access that memory location, instead of hitting some software cache.
http://www.ibm.com/developerworks/java/library/j-jtp06197.html java Example 3 is a memory location whose content is subject to change by external systems outside the JVM. Even if your system never modifies state of the object, it can change any time.
Q10: what are the optimzations? I guess all of them are about memory/caching
A: http://en.wikipedia.org/wiki/Volatile_variable#In_C_and_C.2B.2B shows an example.
Now, A9.1 also applies to java volatile, but java volatile has additional meanings, with concurrency implications. C++ volatile has no such additional. Many authors state that volatile is worthless as a c++ threading construct.
Q: So what is c++ volatile for? Arcane question. In reality, most programmers should not use it, but interviews like c++ volatile, so here we go
%%A: tighter control over access on the memory location behind the target variable.
The primary usage of volatile keyword in java vs c++ are completely different and unrelated.
Q: other differences between java and c++?
A: java volatile is about multiple threads updating a memory location; c++ is about writers outside the current process.
A: in java, volatile keyword creates memory fence/barrier. I think this is similar to c++atomic data types, but not c++volatile
A: java volatile can only be (static/non-static) fields!
A: java volatile confers atomicity on long/double fields
A: c++ member function can be marked volatile. Effect and meaning is described in https://stackoverflow.com/questions/15283223/volatile-function
A: c++ local variable can be marked volatile. See [[effModernC++]] examples
See also [[c++succintly]] and [[effModernC++]]