在两个相同类的指针之间进行转换的安全性?
假设我有两个不同的类,它们都以相同的内部方式表示二维坐标数据,如下所示:
Let's say I have two different classes, both represent 2D coordinate data in the same internal way like the following:
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"
};
鉴于这两个类和上面的函数是相同的,我能否可靠地指望这种指针转换在每种情况下都能按预期工作?
Given the two classes being identical and the function above, can I reliably count on this pointer conversion working as expected in every case?
(背景是,我需要一种简单的方法在两个具有相同 Vertex 类的独立库之间交换顶点数组,并且我想避免不必要地复制数组).
(The background, is that I need an easy way of trading vertex arrays between two separate libraries that have identical Vertex classes, and I want to avoid needlessly copying arrays).
推荐答案
C++11 添加了一个名为 layout-compatible 的概念,适用于此处.
C++11 added a concept called layout-compatible which applies here.
如果两个标准布局结构(第 9 条)类型具有相同数量的非静态数据成员和相应的非静态数据成员,则它们是布局兼容(按声明顺序)具有布局兼容类型(3.9).
Two standard-layout struct (Clause 9) types are layout-compatible if they have the same number of non-static data members and corresponding non-static data members (in declaration order) have layout-compatible types (3.9).
哪里
标准布局类是这样一个类:
A standard-layout class is a class that:
- 没有非标准布局类(或此类类型的数组)或引用类型的非静态数据成员,
- 没有虚函数 (10.3) 和虚基类 (10.1),
- 对所有非静态数据成员具有相同的访问控制(第 11 条),
- 没有非标准布局的基类,
- 要么在最派生的类中没有非静态数据成员且至多有一个具有非静态数据成员的基类,要么没有具有非静态数据成员的基类,并且
- 没有与第一个非静态数据成员相同类型的基类.
standard-layout struct 是使用 class-key struct
定义的 standard-layout class 或class-key class
.
A standard-layout struct is a standard-layout class defined with the class-key struct
or the class-key class
.
standard-layout union 是使用 class-key union
定义的 standard-layout 类.
A standard-layout union is a standard-layout class defined with the class-key union
.
终于
指向 cv-qualified 和 cv-unqualified 版本 (3.9.3) 的布局兼容的指针类型应具有相同的值表示和对齐要求(3.11).
Pointers to cv-qualified and cv-unqualified versions (3.9.3) of layout-compatible types shall have the same value representation and alignment requirements (3.11).
这保证了 reinterpret_cast
可以将指向一种类型的指针转??换为指向任何布局兼容类型的指针.
Which guarantees that reinterpret_cast
can turn a pointer to one type into a pointer to any layout-compatible type.
相关文章