I’m trying to implement the equivalent of the Linux macro ACCESS_ONCE in c++11.
ACCESS_ONCE(x) takes the address of x, casts to a pointer to a volatile of the same type as x, then dereferences it. This forces the compiler to not optimize out accesses to x through this macro (and make the access occur only once here).
My attempt to do it in c++11 involves decltype:
#define ACCESS_ONCE(x) (*static_cast<decltype(x) volatile *>(&(x)))
This works for most cases but I use it once like so:
void foo(void **bar) {
while (ACCESS_ONCE(*bar) != NULL)
;
}
This fails with an error:
'volatile' qualifiers cannot be applied to 'void*&'
What am I doing wrong?
Change the macro to this:
Dereferencing a pointer results in a reference. The macro is trying to cast it to a
void *& volatileinstead of avoid * volatilelike you want. You can’t apply the volatile qualifier to a reference type so you have to use std::remove_reference to change it to the normal non-reference type.