Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean when a member function is volatile? [duplicate]

Tags:

c++

I normally see the const specifier used to indicate a const member function. But what does it mean when the volatile keyword is used?

void f() volatile {}

This compiles fine for me but I don't understand what this is for. I couldn't find any information about this in my search so any help is appreciated.

Update: To make it clear, I know what volatile is for. I just don't know what it means in this context.

like image 744
David G Avatar asked May 25 '13 03:05

David G


People also ask

What is volatile member function in C++?

volatile means two things − - The value of the variable may change without any code of yours changing it. Therefore whenever the compiler reads the value of the variable, it may not assume that it is the same as the last time it was read, or that it is the same as the last value stored, but it must be read again.

Can static member functions be volatile in C++?

A static member function cannot be declared with the keywords virtual , const , volatile , or const volatile .

Can a function be volatile?

Volatile functions are functions in which the value changes each time the cell is calculated. The value can change even if none of the function's arguments change. These functions recalculate every time Excel recalculates. For example, imagine a cell that calls the function NOW .

What is volatile const in C?

The const keyword specifies that the pointer cannot be modified after initialization; the pointer is protected from modification thereafter. The volatile keyword specifies that the value associated with the name that follows can be modified by actions other than those in the user application.


1 Answers

On a member function, const and volatile qualifiers apply to *this. Accesses of any instance members within that member function would then be volatile accesses, with the same semantics as any volatile variable. In particular, non-volatile member functions cannot be called on a volatile object, and volatile applies to overloading in the same way as const:

#include <iostream>

class C {
public:

    void f() {
        std::cout << "f()\n";
    }

    void f() const {
        std::cout << "f() const\n";
    }

    void f() volatile {
        std::cout << "f() volatile\n";
    }

    void f() const volatile {
        std::cout << "f() const volatile\n";
    }

};

int main() {

    C c1;
    c1.f();

    const C c2;
    c2.f();

    volatile C c3;
    c3.f();

    const volatile C c4;
    c4.f();

}
like image 101
Jon Purdy Avatar answered Oct 26 '22 21:10

Jon Purdy