c++ - reinterpret_cast 为相同类型

标签 c++ c++14 standards reinterpret-cast

考虑以下程序:

struct A{};

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

编译器 (g++14) 抛出有关从类型“A”到类型“A”的无效转换的错误。 为什么转换为相同类型无效?

最佳答案

这是不允许的,因为标准是这么说的。

您可以使用reinterpret_cast 执行一组相当有限的允许转换。参见例如cppreference 。例如,列出的第一点是:

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)

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

关于c++ - reinterpret_cast 为相同类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58429179/

相关文章:

Portlet 的 CSS 最佳实践

c++ - 根据标准,整数中的值表示位数?

c++ - 有什么方法可以使用 boost 库实现 Excel LINEST 函数?

c++ - 类成员 `B` 的析构函数,为什么在下面的代码片段中调用它?

c++ - VS2008 在特定的大型 C++ 解决方案上非常慢

c++ - C++ 14和c++ 17中相同代码的不同输出

c++ - 在 C++ 中使用显式原型(prototype)进行返回类型推导

javascript - 为什么 touchDown 和 mouseDown 不能组合起来?

c++ - VC++ 6.0 中的 Cfitsio 错误

c++ - 错误 : ‘std::sin(x)’ cannot be used as a function