为什么从字符串转换常数为'字符*'有效的C,但无效在C ++中 [英] Why is conversion from string constant to 'char*' valid in C but invalid in C++
问题描述
在C ++ 11标准(ISO / IEC 14882:2011)说,在§C.1.1
:
The C++11 Standard (ISO/IEC 14882:2011) says in § C.1.1
:
char* p = "abc"; // valid in C, invalid in C++
对于C ++没关系作为一个指向字符串文字是有害的,因为任何试图修改它会导致崩溃。但是为什么它有效使用C?
For the C++ it's OK as a pointer to a String Literal is harmful since any attempt to modify it leads to a crash. But why is it valid in C?
在C ++ 11也说:
The C++11 says also:
char* p = (char*)"abc"; // OK: cast added
这意味着如果一个铸件添加到第一语句它变为有效。
Which means that if a cast is added to the first statement it becomes valid.
为什么铸造使得第二条语句在C ++中有效,它是如何从第一个有什么不同?是不是还是有害?如果是的话,为什么没有标准说,这是确定?
Why does the casting makes the second statement valid in C++ and how is it different from the first one? Isn't it still harmful? If it's the case, why did the standard said that it's OK?
推荐答案
向上穿过C ++ 03,你的第一个例子是有效的,但使用了德precated隐式转换 - 一个字符串文字应被视为是类型字符常量*
,因为你不能修改其内容(而不会导致不确定的行为)。
Up through C++03, your first example was valid, but used a deprecated implicit conversion--a string literal should be treated as being of type char const *
, since you can't modify its contents (without causing undefined behavior).
由于C ++ 11,依赖于它(如您的第一个例子)的隐式转换已被德precated被正式删除,因此code不应再编译。
As of C++11, the implicit conversion that had been deprecated was officially removed, so code that depends on it (like your first example) should no longer compile.
您已经注意到的一种方式,让code编译:虽然隐式转换已被删除,一个的明确的转换仍然有效,所以你可以添加一个演员。我的不的,但是,考虑这个固定的code。
You've noted one way to allow the code to compile: although the implicit conversion has been removed, an explicit conversion still works, so you can add a cast. I would not, however, consider this "fixing" the code.
真正固定code需要改变指针的类型正确的类型:
Truly fixing the code requires changing the type of the pointer to the correct type:
char const *p = "abc"; // valid and safe in either C or C++.
至于为什么它被允许在C ++(现在仍然是在C):只是因为有很多现有的code的是依赖于隐式转换,并打破了code(至少没有一些官员警告)显然似乎标准委员会像一个坏主意。
As to why it was allowed in C++ (and still is in C): simply because there's a lot of existing code that depends on that implicit conversion, and breaking that code (at least without some official warning) apparently seemed to the standard committees like a bad idea.
这篇关于为什么从字符串转换常数为'字符*'有效的C,但无效在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!