8

如果我做:

const char* const_str = "Some string";

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

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

未定义的行为到底在哪里(哪一行)?

我在 SO 上搜索了很多,但没有找到任何明确和准确的答案(或者至少没有我能理解的答案)。

也相关:如果我使用提供这种功能的外部库:

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

可以这样写:

std::string str = "My string";

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

既然我确定read_string()永远不会尝试写信给str?

谢谢你。

4

2 回答 2

9

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.

于 2011-04-04T07:58:39.407 回答
-1

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";
于 2011-04-04T07:59:46.790 回答