Question

I am experimenting with const_cast operator and trying to override a const status of the parameter o passed as an argument:

void function1 (const Object *o)
{
    ...
    function2( const_cast < Object *> ( o ) ); //Exception in g++
}

void function2 (Object *o) {}

But overriding a const status of o throws an exception in g++ (GNU/Linux), in VS 2010 (Win) it works well ...

Is there any more reliable way how to override a const status of a function parameter?

Update:

MSDN write: You cannot use the const_cast operator to directly override a constant variable's constant status :-(.

Was it helpful?

Solution

MSDN write: You cannot use the const_cast operator to directly override a constant variable's constant status :-(.

const_cast allows you to strip const specifier from the pointer, but it does not affect the "const status" of the value itself. Compiler might decide to put the value into read-only memory (well, it's const!) and then an attempt to modify it, even through const_cast, might result in access violation.

Here is a code snippet:

static const int A = 1; // it's constant, it might appear on a read-only memory page
static int B = 2; // it's a regular variable

const int* pA = &A; // a const pointer
int* pB1 = &B; // a pointer
const int* pB2 = &B; // a const pointer to regular variable

*pA = 0; // Compiler error, we are not allowed to modify const
*const_cast<int*>(pA) = 1; // Runtime error, although const specifier is stripped from the variable, it is still on read-only memory and is not available for updates
*pB1 = 2; // OK
*pB2 = 3; // Compiler error, we are not allowed to modify const
*const_cast<int*>(pB2) = 4; // OK, we stripped const specifier and unlocked update, and the value is availalbe for update too because it is a regular variable

That is, const_cast removes const specifier during compile time, however it is not its purpose, authority or design to alter access mode of the underlying memory.

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