加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:08:28 所属栏目:百科 来源:网络整理
导读:假设我有两个不同的类,它们都以相同的内部方式表示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,bu
假设我有两个不同的类,它们都以相同的内部方式表示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"
};

给定两个类是相同的和上面的功能,我可以可靠地指望这个指针转换工作如预期在每一种情况?

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

解决方法

C 11在这里添加了一个称为布局兼容的概念.

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:

  • has no non-static data members of type non-standard-layout class (or array of such types) or reference,
  • has no virtual functions (10.3) and no virtual base classes (10.1),
  • has the same access control (Clause 11) for all non-static data members,
  • has no non-standard-layout base classes,
  • either has no non-static data members in the most derived class and at most one base class with non-static data members,or has no base classes with non-static data members,and
  • has no base classes of the same type as the first non-static data member.

A standard-layout struct is a standard-layout class defined with the class-key struct or the class-key class.

A standard-layout union is a standard-layout class defined with the class-key union.

最后

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可以将指向一种类型的指针转??换为指向任何布局兼容类型的指针.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读