Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ volatile member functions

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.

like image 722
0xbadf00d Avatar asked Jan 28 '11 09:01

0xbadf00d


People also ask

Can a function be volatile in C?

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.

What is volatile member function in C++?

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.

What are const member functions MC?

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.

What is member function in C?

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.


1 Answers

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.

like image 85
templatetypedef Avatar answered Sep 17 '22 14:09

templatetypedef