Op 25-Apr-15 20:28, Paul schreef:
> Code from C++ Primer is:
>
> const char* pc;
> char * p = const_cast<char*>(pc); // Ok but writing through p is undefined.
>
> Why is writing through p undefined? I thought this was an archetypal
> use of const_cast -- create a non-const object from a low-level const
> object.
Nope, const_cast does not create a new non-const object, it only tells
the compiler: "you may think this is a pointer to a const object, but
take my word for it: it really points to a non-const object". You'd
better be right, or the compiler will have its revenge.
> Why is this use of const_cast wrong?
pc is not initialized in the example; the effects of reading or writing
through an uninitialized pointer is undefined.
But even if it were initialized writing to it is still undefined if pc
is pointing to a const object (this is probably the point C++ Primer is
trying to make). const objects may have been been placed in read-only
memory, making it impossible to modify them.
const_cast<> should only be used to cast away constness if you are
absolutely sure that the object being referred to really is non-const.
For example:
int main()
{
char[1] data; // non-const object
foo(data);
return 0;
}
void foo(const char* pc)
{
bar(pc);
}
void bar(const char* pc)
{
char* p= const_cast<char*>(pc);
p[0] = '!'; // Ok, because pc is really pointing to a non-const object
}
Normally you should never have to use const_cast unless there is some
code you cannot change that passes pointers it got from your code back
to your code. If you need to cast it often indicates there a design issue.