Re: plz xplain behavior of const_cast
On Jan 5, 8:01 am, Heck <heckja...@ordertostymieharvestersverizon.net>
wrote:
const int NUM_UNIVS = -1;
{
// some block of code, and at the end of the block,
// I now have the value I need for NUM_UNIVS,
// so I do the following to assign it the new value
int * tmp;
*(tmp = const_cast <int*> (& NUM_UNIVS)) = new_value;
This is where your code is broken. It is undefined behavior to use
const_cast to cast the const away from a const object, and &NUM_UNIVS
is const int*. Everything else stems from there, see below.
You can only use const_cast on variables that were __initially__
defined as non const. So for example, this is OK:
int i=1;
const int& r = i;
const_cast<int&>(r) = 2;
(Note the use of int&, not int*, to lower syntactical gibberish.)
}
Then, I begin the operations that require NUM_UNIVS, but, this first
condition was failing upon its very first test and the loop was of
course being skipped:
for( univ_num = 0; univ_num <= NUM_UNIVS; ++univ_num)
{
...
The assembly language showed that, indeed, where I expected there to
be a reference to the new value of NUM_UNIVS from the stack, there was
no such. Instead the cmp was made with a -1 literal.
Yes. You said that NUM_UNIVS is const, and equals -1. So compiler took
the freedom to replace it with -1, which is a common optimization.
This, again, is a consequence of language rule that const_cast is
legal only if done on an object (or a reference to it) that was
defined as non-const.
The rule is good, and you broke it ;-). Further, in C++, there's no
reason for the contortion you tried. I am guessing that you want
NUM_UNIVS to be seen as const to a (significant) part of your code,
but you want to change it in some other parts. You can solve that
problem in a different way. For example:
file1.cpp
namespace { int NUM_UNIVS=-1; }
const int& NumUnivs = NUM_UNIVS;
int NumUnivs() { return NUM_UNIVS; }
void ChangesNumUnivs()
{
workworkwork;
NUM_UNIVS=9;
}
file1.h
extern const int& NumUnivs; // Use this to access a read-only variant
of NUM_UNIVS.
file2.cpp
#include file1.h
void f()
{
for (int i=0; i<NumUnivs; i++)
workworkwork;
}
Goran.