Why is conversion from string constant to #39;char*#39; valid in C but invalid in C++(为什么从字符串常量到char *的转换在C中有效但在C++中无效)
问题描述
C++11 标准 (ISO/IEC 14882:2011) 在 § C.1.1
中说:
The C++11 Standard (ISO/IEC 14882:2011) says in § C.1.1
:
char* p = "abc"; // valid in C, invalid in C++
对于 C++ 来说,这是可以的,因为指向字符串文字的指针是有害的,因为任何修改它的尝试都会导致崩溃.但为什么它在 C 中有效?
For the C++ it's OK as a pointer to a String Literal is harmful since any attempt to modify it leads to a crash. But why is it valid in C?
C++11 还说:
char* p = (char*)"abc"; // OK: cast added
这意味着如果将强制转换添加到第一个语句中,它将变为有效.
Which means that if a cast is added to the first statement it becomes valid.
为什么强制转换使第二个语句在 C++ 中有效,它与第一个语句有何不同?不还是有害吗?如果是这样,为什么标准说没问题?
Why does the casting makes the second statement valid in C++ and how is it different from the first one? Isn't it still harmful? If it's the case, why did the standard said that it's OK?
推荐答案
在 C++03 之前,您的第一个示例是有效的,但使用了不推荐使用的隐式转换——字符串文字应被视为 char const *
,因为你不能修改它的内容(不会导致未定义的行为).
Up through C++03, your first example was valid, but used a deprecated implicit conversion--a string literal should be treated as being of type char const *
, since you can't modify its contents (without causing undefined behavior).
从 C++11 开始,已弃用的隐式转换已被正式删除,因此依赖它的代码(如您的第一个示例)不应再编译.
As of C++11, the implicit conversion that had been deprecated was officially removed, so code that depends on it (like your first example) should no longer compile.
您已经注意到允许代码编译的一种方法:虽然隐式转换已被删除,但 显式 转换仍然有效,因此您可以添加强制转换.但是,我不会考虑这种修复"代码.
You've noted one way to allow the code to compile: although the implicit conversion has been removed, an explicit conversion still works, so you can add a cast. I would not, however, consider this "fixing" the code.
真正修复代码需要将指针的类型更改为正确的类型:
Truly fixing the code requires changing the type of the pointer to the correct type:
char const *p = "abc"; // valid and safe in either C or C++.
至于为什么它在 C++ 中被允许(并且仍然在 C 中):仅仅是因为有很多现有的代码依赖于隐式转换,并且破坏该代码(至少没有一些官方警告)显然似乎标准委员会是个坏主意.
As to why it was allowed in C++ (and still is in C): simply because there's a lot of existing code that depends on that implicit conversion, and breaking that code (at least without some official warning) apparently seemed to the standard committees like a bad idea.
这篇关于为什么从字符串常量到'char *'的转换在C中有效但在C++中无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么从字符串常量到'char *'的转换在C中有效但在C++中无效
基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01