c++ - 将字符串文字分配给 char*

标签 c++ pointers c++11 deprecated string-literals

以下代码在 C++0x 中是合法的、弃用的还是非法的?

char* p = "foobar";

我最初问这个问题 here作为评论。

最佳答案

转换

char* p = "foobar";

在 C++98/C++03 中被弃用,并在 C++0x 中被移除(即,§4.2/2 被移除)。

因此,该代码在 C++0x 中无效

但是,MinGW g++ 4.4.1 仍然只发出警告,不发出错误。

C++98/C++03 §4.2/2 (which is removed in C++0x):


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++ - 将字符串文字分配给 char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6492410/

相关文章:

objective-c - 如何在 C 中使用一元指针运算符 (*)?

c - 这段代码的输出是什么以及如何输出?

c++ - 我如何理解我的 valgrind 错误消息?

c++ - 钻石传承

c++ - 我应该使用哪个 *_cast 将任意整数类型的指针转​​换为 char 指针?

c++ - 类成员变量的decltype,是否被禁止?为什么?

c++11 - 声明后定义lambda函数?

c++ - 无法访问派生类方法

c++ - Linux:通过句柄从 boost::thread 获取线程 ID

c++ - 在 C++ 中我的头文件中应该放什么?