Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

No, it just removes const attribute at compile time.

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

const does not change the representation of a type, in particular, the representation of T* is exactly the same as T const*.

Consider:

int i, 
    * const cpi = &i,
    * const * pcpi = &cpi;
int const * const * pcpci = pcpi; // cpi is now int const*

The representation of cpi at the same time represents an int* and a int const* via *pcpci.

There is no way for the representation of cpi to change when pcpci is initialised.

Of course, if the pointer objects have non-significant bits, the compiler can flip them randomly; in particular, const_cast can flip the non-significant bits of a pointer, but any implicit conversion could also. I don't think this case exists in the real world.

The same apply when two different bit patterns result in the same address value (base+offset when offset is big enough).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top