Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c++ > #13113

Re: plz xplain behavior of const_cast

From jt@toerring.de (Jens Thoms Toerring)
Newsgroups comp.lang.c++
Subject Re: plz xplain behavior of const_cast
Date 2012-01-05 09:04 +0000
Organization Freie Universitaet Berlin
Message-ID <9ml7c6FismU1@mid.uni-berlin.de> (permalink)
References <99gag79ess5jgiiap1da1ggotvh8sv55is@4ax.com>

Show all headers | View raw


Heck <heckja_in@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;
> }

> 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.

> 01151906  mov        dword ptr [ebp-0B74h],0  ; num_univ = 0  
> 01151910  jmp         main+3D1h (1151921h)  
> 01151912  mov        eax,dword ptr [ebp-0B74h] 
> 01151918  add         eax,1                            ; ++num_univ
> 0115191B  mov       dword ptr [ebp-0B74h],eax  
> 01151921  cmp        dword ptr [ebp-0B74h],0FFFFFFFFh  
> 01151928  jg            01151AD6 
>  
> The debugger (VS 2010) showed the value of NUM_UNIVS to have been
> changed, but the code generator, written by people who consider
> themselves far more serious than mere writers of debuggers, saw that
> initialization of the const int to -1 and wrote that value in
> everywhere NUM_UNIVS appears, many other locations.  Isn't this the
> way to change the value of a const?  If it can't be changed like this,
> why did the compiler allow it and why  does the debugger respect it?

You can't change a const variable, trying to do so results
in undefined behaviour. And you did your very best to con-
fuse the compiler and you now suffer the consequences;-)

A const cast can be only used reasonably on pointers (or
references) to variables that actually aren't const. An
example would be a function that receives a const pointer
to something that isn't a constant in the caller. Then you
may use the const cast to change the value of what's poin-
ted to anyway (admittedly that's ugly but there can be
circumstances were this can't be avoided). But when what
is pointed to is constant then this won't work. So a const
cast is not for circumventing a variable being constant -
and that seems to be your main misunderstanding. When its
constant it stays constant and nothing can be done about
that afterwards. All you can do is assign the value to a
non-constant variable and then change that.

By qualifying 'NUM_UNIVS' as constant you thus allow the
compiler to reasonably assume that the value of this va-
riable will never change - and it does use this bit of
information to optimize your program. That's completely
legal for the compiler since you're not allowed to change
its value and attempting to do it anyway results in unde-
fined behaviour, i.e. everything can happen and you can't
know what that will be (unless, may be, if you know exact-
ly how the compiler does its job and don't care if this
program will still work when compiled with a different
compiler). The optimization in this case consists of re-
placing 'NUM_UNIVS' in the loop condition by the constant
value of that variable, -1.

To avoid the compiler noticing you don't try to change
'NUM_UNIVS' directly - in that case the compiler would
have told you that you're doing something illegal. You
had to resort to using a pointer and, by using the const
cast, you also basically told the compiler "I know better
than you, don't complain if this looks wrong". So the
compiler really isn't to blame here. You entered a
marked minefield, i.e. attempt to do something for which
the language doesn't define what will be the results (and
thus the compiler may create whatever code it likes),
and got blown up.

Rather likely 'NUM_UNIVS' here is a variable with block
scope and not a global. Otherwise the compiler may have
put it into memory flagged as read-only. And in that case
already the attempt to alter its value via a const cast
pointer might have resulted in a different outcome, a
segmentation fault due to a write access to memory you
are not allowed to modify. That would have been a dif-
ferent symptom of invoking undefined behaviour.

                          Regards, Jens
-- 
  \   Jens Thoms Toerring  ___      jt@toerring.de
   \__________________________      http://toerring.de

Back to comp.lang.c++ | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

plz xplain behavior of const_cast Heck <heckja_in@ordertostymieharvestersverizon.net> - 2012-01-05 02:01 -0500
  Re: plz xplain behavior of const_cast Christian Gollwitzer <auriocus@gmx.de> - 2012-01-05 08:53 +0100
  Re: plz xplain behavior of const_cast "Alf P. Steinbach" <alf.p.steinbach+usenet@gmail.com> - 2012-01-05 08:57 +0100
    Re: plz xplain behavior of const_cast gwowen <gwowen@gmail.com> - 2012-01-05 04:00 -0800
      Re: plz xplain behavior of const_cast "Alf P. Steinbach" <alf.p.steinbach+usenet@gmail.com> - 2012-01-05 23:17 +0100
        Re: plz xplain behavior of const_cast Ian Collins <ian-news@hotmail.com> - 2012-01-06 11:38 +1300
        Re: plz xplain behavior of const_cast Gareth Owen <gwowen@gmail.com> - 2012-01-06 06:33 +0000
        Re: plz xplain behavior of const_cast Nick Keighley <nick_keighley_nospam@hotmail.com> - 2012-01-06 00:46 -0800
          Re: plz xplain behavior of const_cast gwowen <gwowen@gmail.com> - 2012-01-06 03:19 -0800
        Re: plz xplain behavior of const_cast Jorgen Grahn <grahn+nntp@snipabacken.se> - 2012-01-07 06:38 +0000
          Re: plz xplain behavior of const_cast 88888 Dihedral <dihedral88888@googlemail.com> - 2012-01-07 03:53 -0800
      Re: plz xplain behavior of const_cast Juha Nieminen <nospam@thanks.invalid> - 2012-01-06 09:14 +0000
  Re: plz xplain behavior of const_cast Goran <goran.pusic@gmail.com> - 2012-01-04 23:55 -0800
  Re: plz xplain behavior of const_cast jt@toerring.de (Jens Thoms Toerring) - 2012-01-05 09:04 +0000
  Re: plz xplain behavior of const_cast Heck <heckja_in@ordertostymieharvestersverizon.net> - 2012-01-05 09:36 -0500

csiph-web