将字符串文字分配给 char*

发布于 2024-11-17 11:32:27 字数 206 浏览 4 评论 0原文

以下代码在 C++0x 中合法、不推荐使用还是非法?

char* p = "foobar";

我最初在此处作为评论提出了这个问题。

Is the following code legal, deprecated or illegal in C++0x?

char* p = "foobar";

I originally asked this question here as a comment.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凑诗 2024-11-24 11:32:28

该转换

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(在 C++0x 中已删除):


非宽字符串文字的字符串文字 (2.13.4) 可以转换为“pointer to char”类型的右值;宽字符串文字可以转换为“指向 wchar_t 的指针”类型的右值。无论哪种情况,结果都是指向数组第一个元素的指针。仅当存在显式适当的指针目标类型时才考虑此转换,而不是在一般需要从左值转换为右值时考虑。 [注意:此转换已弃用。参见附录 D。] 出于重载决策排序的目的 (13.3.3.1.1),此转换被视为数组到指针的转换,后跟限定转换 (4.4)。 [示例:"abc" 作为数组到指针的转换转换为“指向 const char 的指针”,然后转换为“指向 char 的指针” 作为资格转换。 ]

The conversion

char* p = "foobar";

is deprecated in C++98/C++03, and has been removed (that is, §4.2/2 removed) in C++0x.

So, the code is not valid in C++0x.

However, MinGW g++ 4.4.1 still only emits a warning, not error.

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. ]

擦肩而过的背影 2024-11-24 11:32:28

我相信这在 C++0x 中现在是非法的。 C++03 对遗留代码的这种转换有一个特殊的警告,但 C++0x 删除了它,现在你违反了 const 正确性。

当然,我不知道是否有真正的编译器删除了它,但他们完全有权利这样做。

I believe that this is now illegal in C++0x. C++03 had a special caveat for this conversion for legacy code, but C++0x removed it and now you are violating const correctness.

Of course, I don't know if any real compilers have removed it, but they would be well within their rights.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文