相关疑难解决方法(0)

两个相同类别的指针之间的铸造安全性?

假设我有两个不同的类,它们以相同的内部方式表示2D坐标数据,如下所示:

class LibA_Vertex{
    public:
    // ... constructors and various methods, operator overloads
    float x, y
};

class LibB_Vertex{
    public:
    // ... same usage and internal data as LibA, but with different methods
    float x, y
};


void foobar(){
    LibA_Vertex * verticesA = new LibA_Vertex[1000];
    verticesA[50].y = 9;
    LibB_Vertex * verticesB = reinterpret_cast<LibB_Vertex*>( vertexA );
    print(verticesB[50].y); // should output a "9"
};
Run Code Online (Sandbox Code Playgroud)

鉴于两个类是相同的并且上面的函数,我可以可靠地指望这个指针转换在每种情况下按预期工作吗?

(背景是,我需要一种简单的方法来交换具有相同Vertex类的两个独立库之间的顶点数组,我想避免不必要地复制数组).

c++ pointers casting

9
推荐指数
1
解决办法
513
查看次数

标签 统计

c++ ×1

casting ×1

pointers ×1