I was reading about volatile member function and came across an affirmation that member function can be both const and volatile together. I didn’t get the real use of such a thing. Can anyone please share their experience on practical usage of having member function as const and volatile together.
I wrote small class to test the same:
class Temp { public: Temp(int x) : X(x) { } int getX() const volatile { return X; } int getBiggerX() { return X + 10; } private: int X; }; void test( const volatile Temp& aTemp) { int x = aTemp.getX(); } int main(int argc, char* argv[]) { const volatile Temp aTemp(10); test(aTemp); return 0; }
You asked for a practical example of volatile member functions. Well i can’t think of one because the only situations i could imagine are so low-level that i would not consider using a member function in the first place, but just a plain struct with data-members accessed by a volatile reference.
However, let’s put a const volatile function into it just for the sake of answering the question. Assume you have a port with address 0x378h that contains 2 integers, 4 bytes each. Then you could write
You are stating
Actually, volatile signals that the value of an object might not be the value last stored into it but is actually unknown and might have been changed in between by external (not observable by the compiler) conditions. So when you read from a volatile object, the compiler has to emulate the exact abstract semantics, and perform no optimizations:
The following already determines what
volatiledoes. Everything can be found in1.9of the Standard. The parameters it talks about are implementation defined things, like the sizeof of some type.