gpt4 book ai didi

c++ - 将字符串文字分配给 char*

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:07:39 26 4
gpt4 key购买 nike

以下代码在 C++0x 中是合法的、弃用的还是非法的?

char* p = "foobar";

我最初问这个问题 here作为评论。

最佳答案

转换

char* p = "foobar";

在 C++98/C++03 中被弃用,并在 C++0x 中被移除(即,§4.2/2 被移除)。

因此,该代码在 C++0x 中无效

但是,MinGW g++ 4.4.1 仍然只发出警告,不发出错误。

C++98/C++03 §4.2/2 (which is removed in C++0x):


A string literal (2.13.4) that is not a wide string literal can be converted to an rvalue of type “pointer to char”; a wide string literal can be converted to an rvalue of type “pointer to wchar_t”. In either case, the result is a pointer to the first element of the array. This conversion is considered only when there is an explicit appropriate pointer target type, and not when there is a general need to convert from an lvalue to an rvalue. [Note: this conversion is deprecated. See Annex D. ] For the purpose of ranking in overload resolution (13.3.3.1.1), this conversion is considered an array-to-pointer conversion followed by a qualification conversion (4.4). [Example: "abc" is converted to “pointer to const char” as an array-to-pointer conversion, and then to “pointer to char” as a qualification conversion. ]

关于c++ - 将字符串文字分配给 char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6492410/

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