开发者

Assigning string literals to char*

开发者 https://www.devze.com 2023-03-15 11:56 出处:网络
Is the following code legal, deprecated o开发者_开发技巧r illegal in C++0x? char* p = \"foobar\";

Is the following code legal, deprecated o开发者_开发技巧r illegal in C++0x?

char* p = "foobar";

I originally asked this question here as a comment.


The conversion

char* p = "foobar";

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

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

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

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


I believe that this is now illegal in C++0x. C++03 had a special caveat for this conversion for legacy code, but C++0x removed it and now you are violating const correctness.

Of course, I don't know if any real compilers have removed it, but they would be well within their rights.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号