Why can a string literal be implicitly converted t

2019-04-04 15:51发布

问题:

This question already has an answer here:

  • Why is passing a string literal into a char* argument only sometimes a compiler error? 6 answers
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.