reinterpret_cast为相同类型 [英] reinterpret_cast to the same type

查看:106
本文介绍了reinterpret_cast为相同类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下程序:

struct A{};

int main()
{
    A a;
    A b = a;
    A c = reinterpret_cast<A>(a);
}

编译器(g ++ 14)抛出有关<$ c $的错误c>从类型 A到类型 A的无效转换。
为什么强制转换为相同类型?

The compiler(g++14) throws an error about invalid cast from type 'A' to type 'A'. Why is casting to the same type invalid?

推荐答案

这是不允许的,因为标准如此规定。

It is not allowed, because the standard says so.

使用 reinterpret_cast 可以进行的转换非常有限。参见例如 cppreference 。例如,列出的第一点是:

There is a rather limited set of allowed conversion that you can do with reinterpret_cast. See eg cppreference. For example the first point listed there is:


1)整数,枚举,指针或
指向指针的表达式-成员类型可以转换为自己的类型。结果
的值与expression的值相同。 (自C ++ 11起)

1) An expression of integral, enumeration, pointer, or pointer-to-member type can be converted to its own type. The resulting value is the same as the value of expression. (since C++11)

但是,将自定义类型(无指针!)强制转换为自身不在列表中。您为什么要这么做呢?

However, casting a custom type (no pointer!) to itself is not on the list. Why would you do that anyhow?

这篇关于reinterpret_cast为相同类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆