class MyClass { int x, y; void foo() volatile { // do stuff with x // do stuff with y } };
Do I need to declare x
and y
as volatile
or will be all member variables treated as volatile
automatically?
I want to make sure that "stuff with x
" is not reordered with "stuff with y
" by the compiler.
EDIT: What happens if I'm casting a normal type to a volatile
type? Would this instruct the compiler to not reorder access to that location? I want to pass a normal variable in a special situation to a function which parameter is volatile. I must be sure compiler doesn't reorder that call with prior or followed reads and writes.
Volatile is used in C programming when we need to go and read the value stored by the pointer at the address pointed by the pointer. If you need to change anything in your code that is out of compiler reach you can use this volatile keyword before the variable for which you want to change the value.
Constant and volatile member functions (C++ only) A nonconstant member function can only be called for a nonconstant object. Similarly, a member function declared with the volatile qualifier can be called for volatile and nonvolatile objects. A nonvolatile member function can only be called for a nonvolatile object.
The const member functions are the functions which are declared as constant in the program. The object called by these functions cannot be modified. It is recommended to use const keyword so that accidental changes to object are avoided. A const member function can be called by any type of object.
Member functions are operators and functions that are declared as members of a class. Member functions do not include operators and functions declared with the friend specifier. These are called friends of a class.
Marking a member function volatile
is like marking it const
; it means that the receiver object is treated as though it were declared as a volatile T*
. Consequentially, any reference to x
or y
will be treated as a volatile
read in the member function. Moreover, a volatile
object can only call volatile
member functions.
That said, you may want to mark x
and y
volatile
anyway if you really do want all accesses to them to be treated as volatile
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With