简体   繁体   中英

why can't a volatile object call nonvolatile member function

Why can't a volatile object call a non- volatile member function?

In case of const , it makes sense that calling a non- const member function violates the constness of the the object and hence it is prohibited. But why in the case of volatile ?

In case of const, it makes sense that calling a non-const member function violates the const-ness of the the object and hence it is prohibited. But why in the case of volatile?

It's just the same for volatile. Volatile means every access to an object is a visible side effect and cannot be eliminated. If you called a nonvolatile method on a volatile object, you would violate this property (because the nonvolatile method would treat the object just as a normal object). Therefore, it is impossible.

From the standard:

7.1.5.1. If an attempt is made to refer to an object defined with a volatile-quailified type through the use of an lvalue with a non-volatile-quailified type, the program behaviour is undefined.

I'm guessing your compiler posts an error to prevent undefined behavior. The standard stating so should be reason enough.

The volatile qualifier works much in the same way as const works. To see what can be done thanks to this, take a look at this Alexandrescu article . That article should also give you some insight into the why .

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