简体   繁体   English

使用const_cast <>时未定义的行为在哪里?

[英]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). 我已经在SO上进行了大量搜索,但是没有找到任何明确而准确的答案(或者至少没有我能理解的答案)。

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 ? 既然我可以肯定read_string() 永远不会尝试写入str

Thank you. 谢谢。

Line (2) has undefined behaviour. 第(2)行的行为不确定。 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. 编译器可以自由地将常量放置在只读存储器中(在Windows中,这曾经是一个“数据段”),因此对其进行写操作可能会导致程序终止。 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. 不幸的是,在调用定义不明确的库函数(应为const的非const参数)时,必须舍弃const-ness并不罕见。 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";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM