That is correct. Let’s say you had the following code:
const char hello[] = "hello, world!";
char* jello = hello; // Not allowed, because:
jello[0] = 'J'; // Undefined behavior!
Whoops! A const char*
is a non-const pointer to const char
. If you assign its value to a non-const char*
, you’ve lost its const
property.
A const
pointer to non-const char
would be a char* const
, and you can initialize a char*
from that all day if you want.
You can, if you really want, achieve this with const_cast<char*>(p)
, and I occasionally have, but it’s usually a sign of a serious design flaw. If you actually get the compiler to emit instructions to write to the memory aliased by a string constant, you get undefined behavior. One of the many things that might go wrong is that some implementations will store the constant in read-only memory and crash. Or the same bytes of memory might be re-used for more than one purpose, because after all, we warned you never to change it.
By the way, the rules in C are different. This is solely for backward-compatibility with early versions of C that did not have the const
keyword, and you should never write new code that uses a non-const alias to a string constant.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…