开发者

Where is the undefined behavior when using const_cast<>?

If I do:

const char* const_str = "Some string";

char* str = const_cast<char*>(const_str); // (1)

str[0] = "P"; // (2)

Where (which line) exactly is开发者_开发百科 the undefined behavior ?

I've been searching a lot for this on SO but haven't found any explicit and precise answer (or at least, none that I could understand).

Also related: if I use an external library which provides this kind of function:

// The documentation states that str will never be modified, just read.
void read_string(char* str);

Is it ok to write something like:

std::string str = "My string";

read_string(const_cast<char*>(str.c_str()));

Since I know for sure that read_string() will never try to write to str ?

Thank you.


Line (2) has undefined behaviour. The compiler is at liberty to place constants in read-only memory (once upon a time in Windows this would have been a "data segment") so writing to it might cause your program to terminate. Or it might not.

Having to cast const-ness away when calling a poorly-defined library function (non-const parameter which should be const) is, alas, not unusual. Do it, but hold your nose.


You are attempting to modify a constant string which the compiler may have put into a read-only section of the process. This is better:

char str[32];
strcpy(str, "Some string");
str[0] = "P";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜