比方说,我有两个不同的类,均表示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"
};
,我可以可靠地在该指针转换计数在每种情况下按预期工作? (背景是,我需要一个简单的方法来交换具有相同顶点类的两个独立库之间的顶点数组,并且我希望避免不必要的复制数组)。
做这些转换的另一个明确的方法是使用具有共同初始序列的联合(如§9.2/ 19所允许的)。 – Mankarse
哦!那么,C++ 11来拯救。我只是希望这是VS2010决定在樱桃采摘标准时添加的东西。 –
@Clairvoire:这是在实践中始终有效的事情之一,即使被正式禁止。我不指望任何编译器编写者必须“添加”支持。 –