c++ - 了解 reinterpret_cast

标签 c++ operator-keyword reinterpret-cast

以下程序运行没有任何问题,即使类 B 分配的内存不足以容纳类 A 的所有成员。

// CPP code to illustrate the pointer reinterpret
#include <iostream>
using namespace std;

class A {
public:
    void fun_a()
    {
        cout << " In class A\n";
    }
    int Val;
    int Res;
};

class B {

};

int main()
{
    // creating object of class B
    B* x = new B();

    A* new_a = reinterpret_cast<A*>(x);

    // accessing the function of class A
    new_a->fun_a();
    new_a->Val = 10;
    new_a->Res = 20;

    cout << new_a->Val;
    cout << new_a->Res;

    return 0;
}

最佳答案

通过指向 T 的指针进行间接定向,该指针不指向类型 T(或兼容类型)的对象,这会导致未定义的行为。

The following program runs without any issue,

程序似乎可以正常运行是未定义行为的一个例子。

关于c++ - 了解 reinterpret_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56892327/

相关文章:

c++ - 使用运算符 << 将 std::strings 插入 vector 中

c++ - 这个 reinterpret_cast 可以吗

c++ - 使用函数调用初始化枚举值

c++ - 使用 dynamic_pointer_cast 时无法动态转换

java - 除 a=!a 之外的任何用于取反 boolean 变量的快捷运算符

c++ - 如何选择特定的函数重载?

c++ - 反向 P/调用教程?

c++ - 有什么方法可以防止命名空间在 C++ 中添加更多类?

c++ - 二进制读取、reinterpret_cast 和字节顺序

c++ - reinterpret_cast 和结构对齐