In a singly-threaded program, like the one you have shown, this is perfectly safe. Your first call to foo::A()
will execute in its entirety before x = 1
, which executed before the next call to foo::A()
. The second call is always guaranteed to read 1
, unless you have some undefined behavior somewhere else in your program.
In a multi-threaded program, the const
only requires that foo
not change the value of x
, not that other threads don't change its value. Thus, something like this might require synchronization to read this properly. An std::mutex
and/or std::atomic
might help you with that part of it.
As to using volatile
, volatile
isn't really for what you seem to think it is for. It is generally for cases when the variable can be changed outside the context of the compiler. Using volatile
here won't necessarily make your read safer. Use standard synchronization methods instead to ensure your read is safe.
Oh, and by the way, to answer this question:
// prints "0" or "1"??
This prints 1
. You passed it by reference, so changing the value in main()
will change the value stored in foo
. That's one of the advantages, if you will, of passing by reference.