Where the C ++ 11 standard says char * p = "abc"; badly formed?

Where the C ++ 11 standard says char* p = "abc"; poorly formed?

+4
source share
1 answer

This is still relevant in C ++ 03 (although deprecated), but everything has changed to C ++ 11. Appendix C of the C ++ 11 standard mentions (see C1.1) that:

Edit : string literals made by const

The type of the string literal changes from "array of char " to "array of const char ". char16_t type string literal changes from "array of some-integer-type" to "array of const char16_t ". char32_t string literal type changes from "array of some-integer-type" to "array of const char32_t ". The type of the wide string literal varies from "array of wchar_t " to "array of const wchar_t ."

Justification . This avoids the inappropriate overloaded function, which can count on the possibility of changing its argument.

Impact on the original function . Go to the semantics of a well-defined function.

Transformation complexity : syntactic transformation. The fix is ​​to add a cast:

 char* p = "abc"; // valid in C, invalid in C++ void f(char*) { char* p = (char*)"abc"; // OK: cast added f(p); f((char*)"def"); // OK: cast added } 

In C ++ 03, this was an exception to the implicit conversion rules. In C ++ 11, this exception disappeared, which is probably why you could not find the point in the Standard where this case is mentioned.

The paragraph above was added to Appendix C (which is only informative and not normative) so that you can find evidence of a violation.

In any case, the relevant paragraphs 2.14.5 / 8:

UTF-8 plain string literals and string literals are also called narrow string literals. Arrow A string literal is of type " array n const char ", where n is the size of the string, as defined below, and has a static storage duration (3.7).

And 4.4 / 1 (see also 4.2 for conversions from array to pointer):

A value of type "pointer to cv1 T " can be converted to a prvalue of type "pointer to cv2 T " if " cv2 T " is more cv -qualified than " cv1 T ".

+8
source

Source: https://habr.com/ru/post/1489726/


All Articles