问题描述
如果我这样做:
const char * const_str =Some string
char * str = const_cast< char *>(const_str); //(1)
str [0] =P; //(2)
哪里(哪一行)是未定义的行为?
我一直在搜索很多,但没有找到任何明确和精确的答案(或至少,没有一个我能理解)。
也相关:如果我使用外部库提供这样的函数:
//文档声明str永远不会被修改,只是读。
void read_string(char * str);是否可写:
std :: string str =My string;
read_string(const_cast< char *>(str.c_str()));
因为我知道 read_string()
从不尝试写入 str
?
谢谢。 >
行(2)有未定义的行为。编译器可以放置常量在只读存储器(在Windows中一次,这将是一个数据段),因此写入它可能会导致您的程序终止。
在调用一个不太定义的库函数(非const参数,应该是const)时强制转换常量是唉,不是异常。做它,但保持你的鼻子。
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.
这篇关于当使用const_cast<> ;?时,未定义的行为在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!