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?
+2
A:
const_cast just throws away the constness of an attribute and nothing more.
Shree
2009-04-17 07:20:13
+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
2009-04-17 07:24:39
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
2009-04-17 07:47:24
I intentionally didn't say _when_ the compiler would have to emit some code.
anon
2009-04-17 08:08:00
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
2009-04-17 13:39:13
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
2009-06-01 16:53:26