Re: Reference to volatile data
On Apr 14, 7:08 am, stefan <sssste...@gmail.com> wrote:
The C++ standard [ISO 14882:2003] contains the following text:
A pointer or reference to a cv-qualified type need not actually
point or refer to a cv-qualified object, but it is treated as if it
does; a const-qualified access path /.../ [section 7.1.5.1-3]
With that in mind, consider the following code:
const int K = 4;
int foo()
{
const volatile int& r = K;
return r;
}
Is the C++ language actually guaranteeing that the compiler is never
allowed to rewrite foo() to just do "return 4"?
Yes, with qualifications. The definition of a visible aspect of the C+
+ virtual machine leaves the exact definition to the implementation.
Without talking about the actual physical machine, it doesn't make any
sense to say
to rewrite foo() to just do "return 4"?
Let me be clear that as a portable construct, do not use volatile as a
threading construct. It does not work.
(It may work for specific platforms. Check with your implementation
docs, and check the produced assembly. Prefer a portable threading
library that has useful abstractions like mutexes, condition
variables, memory barriers, etc., like Boost, instead of using
volatile directly for such a purpose. Prefer writing your own thin
wrapper if you really can't use a portable threading library and must
roll your own to avoid scattering volatile everywhere.)
As far as I can tell, there are \only\ 3 valid uses of volatile,
something most C and C++ programmers never use.
1- Memory mapped IO. Like writing device drivers.
2- Ensuring a write is not optimized away when working with setjmp /
longjmp.
3- Ensuring a write is not optimized away when working with signal
handlers.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]