c++ - "hello world"string literal 可以赋给char * 类型吗?

标签 c++ string constants

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/

相关文章:

java - 字符串索引超出范围 : -1

c++ - 如何将多个字符组合成一个字符串?

javascript - Node 中的 const,在不同的 block 中

c++ - 创建大量对象指针

c++ - 我可以让 C++ 编译器在编译时实例化对象吗?

c++ - 我如何创建一个线程安全的 QOffscreenSurface 供 OpenGl 使用

c++ - 什么是 Apple GCC 中的 WSAAsyncSelect() 函数模拟?

php - 从 Mysql 获取逗号分隔的字符串

c++ - 恒定值变化

c++ - 如何修改 const 的私有(private)成员?