Friday, February 03, 2006

subtle difference when using const_cast

ive just read this article: http://www.devx.com/tips/Tip/5508 which shows the subtle difference (when is good \ bad) when using the const_cast on objects.

thinking from the point of view of what a variable may contain (its value) and where this value is stored in computer memory, you can think of 2 kinds of const'ness:

a 'true const':

const int cn = 5; // true const variable; it might be stored in computer ROM

and a 'contractual const':

int num = 0;

const int * pci = # // *pci is a contractual const int

if you try to remove the constness of a variable in order to modify its value, its good to know wheater that variable is a 'true' or 'contractual' const.

modifing a 'true' const variable is undefined (and not desirable to do).

the idea is that a pointer to a const variable is still (just) a pointer containig the address of a variable.

that variable, if you know that its not a true const (like const int num = 0) you can modify it safely.

in other words, 'const' can be more than just 'don't change the value', more then a specifier. it might have implications of how the variable is kept in memory.

No comments: