【问题标题】:Why can reinterpret_cast not convert an int to int?为什么 reinterpret_cast 不能将 int 转换为 int?
【发布时间】:2013-09-22 22:24:18
【问题描述】:

我的编译器是最新的 VC++ 2013 RC。

void f()
{
    int n1 = 0;
    int n2 = reinterpret_cast<int>(n1); // error C2440
}

错误 C2440:“reinterpret_cast”:无法从“int”转换为“int”

为什么reinterpret_cast不能用在这么明显的情况下?

【问题讨论】:

  • 听起来像一个错误
  • 有趣,在MSVC2010中也是这样
  • 这也不编译: const int x = 10; int y = const_cast(x);
  • @LuchianGrigore:(我的编译器是最新的 VC++ 2013 RC。)是什么泄露了它? :)

标签: c++ pointers integer type-conversion reinterpret-cast


【解决方案1】:

According 到 cppreference.com 以下转换仅在 C++11 之后可用:

整数、枚举、指针或指向成员的指针的表达式 type 可以转换为自己的类型。结果值是一样的 作为表达式的值。

Visual Studio 2013 RC 中的 may not be implemented

【讨论】:

  • 我认为你是对的。 [C++03: 5.2.10/1] 明确指出只有列出的转换是有效的,而这种自我转换不是其中之一。因此,这与其说是一个 VS 错误,不如说是一个尚未实现的 C++11 功能。
【解决方案2】:

C++ 标准说 (5.2.10.2)(强调我的):

reinterpret_cast 运算符不应抛弃 constness (5.2.11)。 整数、枚举、指针或指向成员类型的表达式可以显式转换为自己的类型;这样的演员产生 其操作数的值。

所以我会说这是一个错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    • 2023-03-09
    • 2014-06-04
    相关资源
    最近更新 更多