简体   繁体   中英

Position of volatile keyword in member function declaration in C++

Does the positioning of the 'volatile' keyword in a method declaration affect its functionality?

ie, is there any difference between the following two pieces of code?

A.

class Test
{
public:
    volatile void testMe() 
    {
    }
};

B.

class Test
{
public:
    void testMe() volatile 
    {
    }
};

And same goes when the member function has a return value. Thank you!

It is the same as for the const qualifier.

In the first example, the volatile applies to the return value of the function. It is void in this case, so it doesn't make much sense. In fact, it doesn't make much sense to return by volatile value * . A volatile return type would only make sense for a reference:

volatile int& foo() { ... }
volatile int& i = foo(); // OK
int j = foo(); // OK, use the volatile reference to construct a non volatile int
int& j = foo(); // Error!

In the second case, it means that the method is volatile , hence it can be called on (non-const) non-volatile and volatile instances of class Test . A similar method without the volatile qualifier could not be called on a volatile instance.

Test test0;
test0.testMe(); // OK
volatile Test test1;
test1.testMe(); // OK
test1.someNonVolatileMethod(); // Error.

* Unless that value is a pointer

The same rules that apply to const apply to volatile .

When returning void (rather not returning), volatile is useless in the first snippet.

The second snippet marks the whole method as volatile .

For example, if you have:

volatile Test m;
m.testMe();

only compiles is testMe is marked as volatile (like your second code).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM