tags:

views:

51

answers:

1

Hi, I heard that volatile nature of a variable can be removed using const_cast operator.

In which scenarios we need to remove volatile nature of a variable ? are there any good use cases ? Is it dangerours operation, because we declared it as volatile thinking that it would be modified by external factors and removing volatile nature could stop modifications to it. Specially when volatile pointers are registers etc.

+2  A: 

The moment you do that, behavior is undefined. Note that removing volatile from an expression that really refers to a non-volatile variable and removing volatile from an expression that refers to a volatile variable are different. The latter thing is what you asked about, and it causes undefined behavior. The Standard laws

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

Johannes Schaub - litb
Which is why `const_cast` is meant for both `const` and `volatile`: both are equivalent here. As for when, think of `int volatile* p = /**/;` if you know that `p` really refers to a non-volatile variable, then removing the `volatile` qualifier will allow you to use it for what it is. It is generally messy though (I think) to mix those things, and I don't really like a `const_cast` appearing in the code.
Matthieu M.