gpt4 book ai didi

c++ - 为什么字符串文字只能在某些情况下隐式转换为 char*?

转载 作者:IT老高 更新时间:2023-10-28 23:10:22 27 4
gpt4 key购买 nike

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 *'
}

代码使用 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.

为什么 f("Hello") 正常?

最佳答案

至少在理论上,这种行为在 C 和 C++ 之间有所不同。

在 C 语言中: 字符串文字衰减为非常量指针。但是,这并不是一个好主意。试图通过该指针修改字符串会导致未定义的行为。

在 C++ 中: 永远不行(AFAIK)。* 但是,一些编译器可能仍然会让你侥幸逃脱。例如,GCC 有 -Wwrite-strings标志,默认启用(至少在 4.5.1 以后)。


* 至少在 C++11 中。 (我手头没有旧规范。)

关于c++ - 为什么字符串文字只能在某些情况下隐式转换为 char*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14415488/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com