如果我做:
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
?
谢谢你。