char* foo = "fpp"; //compile in vs 2010 with no problem
虽然字符串文字是 const char* 类型。
const 类型不能赋值给非 const 类型。
所以我希望上面的代码失败或者我遗漏了什么?
编辑:抱歉各位,我完全忘记了编译器也会抛出警告。
我一直在看错误列表。
我忘了检查那个。
Edit2:我将我的项目警告级别设置为 EnableAllWarnings (/Wall),但没有关于此的警告。
所以我的问题仍然有效。
最佳答案
C++03 反对[引用 1] 使用不带 const
关键字的字符串文字。
[引用 1]C++03 标准:§4.2/2
A string literal (2.13.4) that is not a wide string literal can be converted to an rvalue of type “pointer to char”; a wide string literal can be converted to an rvalue of type “pointer to wchar_t”. In either case, the result is a pointer to the first element of the array. This conversion is considered only when there is an explicit appropriate pointer target type, and not when there is a general need to convert from an lvalue to an rvalue. [Note: this conversion is deprecated. See Annex D. ] For the purpose of ranking in overload resolution (13.3.3.1.1), this conversion is considered an array-to-pointer conversion followed by a qualification conversion (4.4). [Example: "abc" is converted to “pointer to const char” as an array-to-pointer conversion, and then to “pointer to char” as a qualification conversion. ]
C++11 只是删除了上面的引用,这暗示它在 C++11 中是非法代码。
在 C++03 之前,C++ 派生了它的字符串字面量声明而没有 const
关键字,请注意,这在 C 中是完全有效的。
关于c++ - "hello world"string literal 可以赋给char * 类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13248399/