为什么一个字符串文字被隐式转换为char *仅在某些情况下? [英] Why can a string literal be implicitly converted to char* only in certain case?
问题描述
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 *'
}
在code编译用VC ++ 2012年11月CTP。
The code was compiled with VC++ Nov 2012 CTP.
§2.14.15字符串常量,第7节
§2.14.15 String Literals, Section 7
一个窄字符串文字具有其中n是类型为n为const char数组
如下面所定义,并且该字符串的大小具有静态存储
持续时间。
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.
为什么 F(你好)
OK?
推荐答案
此行为C和C之间不同++,至少理论上是这样。
This behaviour differs between C and C++, at least in theory.
在C:字符串文字衰变到一个非const指针。然而,这并不能使它一个好主意;试图通过该指针修改字符串会导致不确定的行为。
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.
在C ++:这是永远OK(据我所知) * 然而,一些编译器仍然可以让你摆脱它。 GCC,例如,有 -Wwrite -strings
标志,这是默认启用的(至少在4.5.1起)。
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).
<子> *在C ++ 11,至少。 (我没有旧的规格手。)
这篇关于为什么一个字符串文字被隐式转换为char *仅在某些情况下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!