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


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

Re: const_cast issue

From Richard Damon <news.x.richarddamon@xoxy.net>
Newsgroups comp.lang.c++
Subject Re: const_cast issue
Date 2011-11-19 12:22 -0500
Organization A noiseless patient Spider
Message-ID <ja8okd$mnb$1@dont-email.me> (permalink)
References <30719501.757.1321527452906.JavaMail.geo-discussion-forums@prdy11>

Show all headers | View raw


On 11/17/11 5:57 AM, asit wrote:
> Just go through the code
> 
>   1 #include <iostream>
>   2 #include <cstdlib>
>   3
>   4 using namespace std;
>   5
>   6 double funct1(double& f)
>   7 {
>   8         f++;
>   9         cout<<"f = "<<f<<endl;
>  10         return f;
>  11 }
>  12
>  13 void funct2(const double& d)
>  14 {
>  15         cout<<"d = "<<d<<endl;
>  16         double value = funct1(const_cast<double&>(d));
>  17         cout<<"value = "<<value<<endl;
>  18         cout<<"d = "<<d<<endl;
>  19 }
>  20
>  21 int main()
>  22 {
>  23         const double c = 4.324;
>  24         funct2(c);
>  25         double &k = const_cast<double&>(c);
>  26         k++;
>  27         cout<<"c = "<<c<<endl;
>  28         cout<<"k = "<<k<<endl;
>  29         return 0;
>  30 }
> 
> 
> At line 27, value is printed as 4.324.
> 
> But at line 28, value is printed as 6.324.
> 
> Can you tell me why even though I am incrementing only once ?

Since c is declared const, the implementation is allowed to assume that
it will not change, and thus when you reference it on line 27, the
implementation is allowed to use the know value, and is not required to
go back to the actually variable to get the value.

By using const_cast to remove the const from an object that was declared
const, you have invoked undefined behavior, which means in part, that
the implementation may end up making assumptions that no longer hold,
like that c has the value 4.324

Undefined behavior means that anything might happen. In your case c has
two different values that might be obtained depending on if the
implementation decides to actually access the value is c or use what it
"knows" it contains. Some other reasonably possible results are that c
doesn't actually change, or that the program is aborted when you
attempted to change the value. Technically, the implementation has been
given by the C++ standard to do anything that it might want to do in
this case, including very bad things like erasing your hard disk or
making your computer turn plaid (of course other rules, like the laws of
nature, may limit what it actually is able to do).

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


Thread

const_cast issue asit <lipun4u@gmail.com> - 2011-11-17 02:57 -0800
  Re: const_cast issue Goran <goran.pusic@gmail.com> - 2011-11-17 04:17 -0800
  Re: const_cast issue Richard Damon <news.x.richarddamon@xoxy.net> - 2011-11-19 12:22 -0500

csiph-web