What is the purpose of a volatile member function in C++?

后端 未结 2 1143
后悔当初
后悔当初 2020-12-08 10:19

What is the purpose of a volatile member function in C++?

2条回答
  •  暖寄归人
    2020-12-08 11:12

    EDIT:

    This answer was posted when the question was about the volatile keyword. Question seems to have been changed by a third party.

    ORIGINAL:

    Volatile informs the compiler that it should not assume that the value it just put in the variable marked as volatile will be there next time it uses it... that it must check the current value before using it again.

    One example is if the variable represents a memory location that might be changed by another process.

    Here's an example (been ages since I did C++ so please forgive any minor syntax issues):

    volatile int x;
    
    int DoSomething()
    {
        x = 1;
    
        DoSomeOtherStuff();
    
        return x+1; // Don't just return 2 because we stored a 1 in x.  
                    // Check to get its current value
    }
    

提交回复
热议问题