gpt4 book ai didi

c++ - 为什么可以将 const char* 分配给 char*?

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

我知道例如 "hello" 的类型是 const char*。所以我的问题是:

  1. 我们如何将像 "hello" 这样的文字字符串分配给非 const char*,如下所示:

    char* s = "hello";  // "hello" is type of const char* and s is char*
    // and we know that conversion from const char* to
    // char* is invalid
  2. 是像"hello"这样的文字字符串,它会占用我所有程序的内存,还是就像临时变量一样,在语句结束时会被销毁?

最佳答案

事实上,"hello" 的类型是 char const[6]

但问题的要点仍然是正确的——为什么 C++ 允许我们将只读内存位置分配给非 const 类型?

这样做的唯一原因是向后兼容不知道 const 的旧 C 代码。如果 C++ 在这里很严格,它会破坏很多现有的代码。

也就是说,大多数编译器都可以配置为警告此类代码已弃用,甚至默认情况下这样做。此外,C++11 完全不允许这样做,但编译器可能还没有强制执行。


对于Standerdese粉丝:
[引用 1]C++03 标准:§4.2/2

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++11 只是删除了上面的引用,这意味着它是 C++11 中的非法代码。

[引用 2]C99 标准 6.4.5/5“字符串文字 - 语义”:

In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence; for wide string literals, the array elements have type wchar_t, and are initialized with the sequence of wide characters...

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

关于c++ - 为什么可以将 const char* 分配给 char*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10268705/

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