将字符串字面量分配给char * [英] Assigning string literals to char*

查看:232
本文介绍了将字符串字面量分配给char *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码是否在C ++ 0x中合法,已弃用或违法?

Is the following code legal, deprecated or illegal in C++0x?

char* p = "foobar";

我最初问这个问题此处作为注释。

I originally asked this question here as a comment.

推荐答案

char* p = "foobar";

在C ++ 98 / C ++ 03中已弃用,

is deprecated in C++98/C++03, and has been removed (that is, §4.2/2 removed) in C++0x.

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

So, the code is not valid in C++0x.

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

However, MinGW g++ 4.4.1 still only emits a warning, not error.


C ++ 98 / C ++ 03§4.2/ 2 (在C ++ 0x中删除):



字符串文字(2.13.4)宽字符串文字可以转换为类型的指针 char 的右值;可以将宽字符串文字转换为类型指向 wchar_t 的右值。在任一情况下,结果都是指向数组的第一个元素的指针。仅当存在明确的适当的指针目标类型时才考虑此转换,而不是在通常需要从左值转换为右值时。 [注意:此转换已弃用。见附件D.]为了在过载分辨率(13.3.3.1.1)中进行排序,这种转换被认为是一个数组到指针的转换,然后是一个资格转换(4.4)。 [示例:abc被转换为指向 const char 的数组到指针转换,然后到指向 char 的指针作为限定转换。 ]

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. ]

这篇关于将字符串字面量分配给char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆