views:

224

answers:

3

Is it true that const_cast is just a way to tell the compiler "stop moaning, treat this as a non-const pointer"? Are there any cases when const_cast itself is translated into actual machine code?

+8  A: 

No, it just removes const attribute at compile time.

Lazin
+2  A: 

const_cast just throws away the constness of an attribute and nothing more.

Shree
+3  A: 

Conceivably,there could be architectures where a const pointer had a different representation to a non-const one, in which case the compiler would have to emit some code. I'm not aware of any such architectures, however.

anon
Clever, but not true: const is attribute only, it does not mean you cannot write (consider mutable members). If you are conceiving an architecture where read-only and read-write or write-only pointers are different, then the code still will not be generated on cast, rather on the write itself.
Suma
I intentionally didn't say _when_ the compiler would have to emit some code.
anon
Doesn't matter at all. The const_cast woud remove the hypothetical "read-only bit" in the pointer, as would writes to a mutable member through a const pointer. The latter can be detected with 100% acuracy by the compiler.
MSalters
Yeah, if anything, then would the conversion need to unset/set the bit. Writes to mutable members don't concern the pointer to the class-type anymore, since at that time, it's already de-referenced. Also note that what can be different at most are the bits that don't participate in the value calculation of the pointer. Those bits that do (value-representation) must be identical for T* and T const* (see 3.9.2/3).
Johannes Schaub - litb