Why can a string literal be implicitly converted to char* only in certain case? [duplicate]

霸气de小男生 提交于 2019-12-21 07:25:31

问题


void f(char* p)
{}

int main()
{
    f("Hello"); // OK

    auto p = "Hello";

    f(p); // error C2664: 'void f(char *)' : cannot convert parameter 1 
          // from 'const char *' to 'char *'
} 

The code was compiled with VC++ Nov 2012 CTP.

§2.14.15 String Literals, Section 7

A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration.

Why is f("Hello") OK?


回答1:


This behaviour differs between C and C++, at least in theory.

In C: a string literal decays to a non-const pointer. However, that doesn't make it a good idea; attempting to modify the string through that pointer leads to undefined behaviour.

In C++: it's never ok (AFAIK).* However, some compilers may still let you get away with it. GCC, for example, has the -Wwrite-strings flag, which is enabled by default (at least in 4.5.1 onwards).


* In C++11, at least. (I don't have older specs to hand.)


回答2:


The difference between

f("Hello");

and

f(p);

is that the former involves a literal. In C++03 conversion from string literal to char* (note: not const) was supported. It isn't supported any longer in C++11, but few if any compilers have yet caught up with that rule change.




回答3:


f("Hello");

Even this is not okay in C++. The compiler should give diagnostic, or else it needs to be updated.

In C++, "Hello" is convertible to const char*, not char*.

The conversion from "Hello" to char* is allowed in C++03, though it is deprecated. And in C++11, the conversion is invalid, and the code is ill-formed.




回答4:


I think because auto keyword. it's type deduction so compiler doesn't know it how to convert to char* anymore.



来源:https://stackoverflow.com/questions/14415488/why-can-a-string-literal-be-implicitly-converted-to-char-only-in-certain-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!