【问题标题】:Is a cast from (pointer to const) to (pointer to non-const) invalid c++?从(指向常量的指针)到(指向非常量的指针)的强制转换是无效的c++吗?
【发布时间】:2023-03-02 21:15:02
【问题描述】:

我确信下面的代码不应该编译。但是,在 g++ 中,它确实可以编译!参见http://codepad.org/MR7Dsvlz 编译。

代码:

#include <iostream>

using namespace std;

int main() {
    int x = 32 ;
    // note: if x is, instead, a const int, the code still compiles, 
    // but the output is "32".

    const int * ptr1 = & x ;

    *((int *)ptr1) = 64 ; // questionable cast
    cout << x ;           // result: "64"
}

编译这个是g++出错了吗?

【问题讨论】:

标签: c++ pointers casting g++ constants


【解决方案1】:

没有。根据 C++ 标准的 §5.4.4,可以通过 C 样式转换执行的转换是:

— a const_cast (5.2.11),
— a static_cast (5.2.9),
— a static_cast followed by a const_cast,
— a reinterpret_cast (5.2.10), or
— a reinterpret_cast followed by a const_cast

这被广泛称为“抛弃const-ness”,如果不编译该代码,编译器将不符合标准的该部分。

正如 ildjarn 指出的那样,通过抛弃 constness 来修改 const 对象是未定义的行为。该程序没有表现出未定义的行为,因为尽管指向const 的指针指向了一个对象,但该对象本身并不是const(感谢 R.Martinho 和 eharvest 纠正了我的错误阅读)。

【讨论】:

  • “没有。” - 所以 g++ 应该已经编译了代码? “如果编译器不编译该代码,它将不符合标准的该部分。” - 所以 g++ 符合标准的那部分?
  • @noshenim 您的问题是“g++ 编译是否出错?”我回答“不”。所以 g++ 应该并且确实编译代码,并且它符合标准的那部分。
  • Noshenim,你问了自相矛盾的问题。对标题问题的任何yes 答案都是对正文问题的no 答案。下次请多加小心。
  • @ildjarn 好的,添加了关于此的注释。
  • 但是被修改的对象不是const。正在修改的对象是int x = 32 ;
【解决方案2】:

没有。通过编译您的代码,g++ 不会出错。你所做的演员是有效的。

(int *)ptr1 是一个 c 演员。 c++ 中的等价物是const_cast&lt;int*&gt;(ptr1)。第二种风格更容易阅读。

但是,需要进行这种转换(修改 const 变量)表明设计存在问题。

【讨论】:

    【解决方案3】:

    *((int *)ptr1) = 64 行等价于 *(const_cast&lt;int*&gt;(ptr1)) = 64 const_cast 是使用转换符号时执行的第一个转换。

    【讨论】:

      猜你喜欢
      • 2020-10-23
      • 2021-06-19
      • 1970-01-01
      • 2013-01-04
      • 1970-01-01
      • 2014-02-23
      • 2017-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多