Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the const_cast<> on a volatile?

I saw it was possible to do it but I do not understand the interest.

like image 595
Dpp Avatar asked Jun 12 '10 22:06

Dpp


2 Answers

const and volatile sound like they refer to the same idea on a variable, but they don't. A const variable can't be changed by the current code. A volatile variable may be changed by some outside entity outside the current code. It's possible to have a const volatile variable - especially something like a memory mapped register - that gets changed by the computer at a time your program can't predict, but that your code is not allowed to change directly. You can use const_cast to add or remove const or volatile ("cv-qualification") to a variable.

like image 132
jwismar Avatar answered Nov 15 '22 18:11

jwismar


const and volatile are orthogonal.

const means the data is read-only.

volatile means the variable could be changing due to external reasons so the compiler needs to read the variable from memory each time it is referenced.

So removing const allows you to write what was otherwise a read-only location (the code must have some special knowledge the location is actually modifiable). You shouldn't remove volatile to write it because you could cause undefined behavior (due to 7.1.5.1/7 - 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.)

like image 44
R Samuel Klatchko Avatar answered Nov 15 '22 19:11

R Samuel Klatchko