reinterpret_cast to the same type

て烟熏妆下的殇ゞ 提交于 2019-12-10 16:01:44

问题


Consider following program:

struct A{};

int main()
{
    A a;
    A b = a;
    A c = reinterpret_cast<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?


回答1:


It is not allowed, because the standard says so.

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) 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?




回答2:


Because reinterpret_cast cannot be used for classes and structures, it should be used to reinterpret pointers, references and integral types. It is very well explained in cpp reference

So, in your case one possible valid expression would be reinterpret_cast<A*>(&a)




回答3:


reinterpret_cast should be used to pointers, references and integral types.

I don't know, Why someone do that.

But Still you want do.You can do like.

 A *d = reinterpret_cast<A*>(&a);

or

A c = reinterpret_cast<A&>(a);


来源:https://stackoverflow.com/questions/58429179/reinterpret-cast-to-the-same-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!