On May 4, 1:17*am, Comp1...@yahoo.co.uk wrote:
> On May 3, 9:36*pm, Comp1...@yahoo.co.uk wrote:
>
> > I've been told that const_cast "adds or removes the constness of an
> > expression".
> > I understand that it converts pointers to const to pointers to non-
> > const and references to const to references to non-const. *But how
> > does a const_cast affect a variable of type const int* const? *I would
> > assume a const_cast would make such a variable have type const int*
> > Is this correct?
>
> > Thanks
>
> Sorrmy I meant that const_cast transforms the type const int* const to
> int* const. *Is this correct?
The following const_cast will transform a variable of type const int*
const to int* const
(It removes constness of the data).
const int i = 10;
const int* const r = &i;
int* const r2 = const_cast<int* const>(r);
However, since the actual data (i) is originally cosnt, any attempt to
change the value of i through r2 will result in undefined behavior.
The following const_cast will tranfrom a variable of type const int*
const to const int*
(It removes constness of the pointer)
const int i = 10;
const int* const r = &i;
const int* r3 = const_cast<const int*> (r);
Note that the const_cast is actually redundant here, since we are
removing "top level" constness for a pointer, which is anyway legal as
we are doing a copy. Had r3 been a reference, then you would need an
explicit const_cast:
const int*& r3 = r; //Error
const int*& r3 = const_cast<const int*&> (r); //Works.
|