从对象到第一个成员的reinterpret_cast [英] reinterpret_cast from object to first member

查看:103
本文介绍了从对象到第一个成员的reinterpret_cast的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看答案,我想知道是否通过reinterpret_cast并使用

I was looking at this answer and I was wondering if casting an object to its first member with reinterpret_cast and using the result could be safe in C++.

让我们假设我们有一个A类,一个B类和一个B实例b:

Let's assume that we have a class A, a class B and an instance b of B:

class A{
public:
    int i;
    void foo(){}
};

class B{
public:
    A a;
};

B b;

问题1:使用ba这样安全吗: reinterpret_cast< A *>(& b)-> foo()

Question 1: Is it safe to use b.a like this: reinterpret_cast<A*>(&b)->foo()?

注意:一般情况下我们假设该类及其成员都是标准布局。

Note: In the general case we suppose that the class and its member are both standard layout.

我在 reinterpret_cast 告诉我,此类使用应得到授权,因为没有混叠违规,但是它与这一个

My lecture of the available references on reinterpret_cast tells me such usage should be authorized as there is no aliasing violation, however it conflicts with many answers like this one.

问题2:使用ba这样安全吗: static_cast< A *>(static_cast< void *>(& b))-> foo()

Question2: Is it safe to use b.a like this: static_cast<A*>(static_cast<void*>(&b))->foo()?

推荐答案

是的,因为这里的两个类都是 standard-layout类型,您可以在& b之间进行转换& ba

Yes, because both classes here are standard-layout types, you can convert between &b and &b.a.

reinterpret_cast< A * >(p)被定义为与 static_cast< A *>(static_cast< void *>(p))相同, (5.2.10p7),所以您的两个问题都相等。

reinterpret_cast<A*>(p) is defined to be the same as static_cast<A*>(static_cast<void*>(p)), (5.2.10p7) so both your questions are equivalent.

对于标准布局类,结构/类的地址与其第一个非结构化类的地址相同-static成员(9.2p19)。并且 static_cast void * 的往返地址将保留地址(5.2.9p13),这意味着结果将是有效的。

For standard-layout classes, the address of the struct/class is the same as the address of its first non-static member (9.2p19). And static_cast to/from void* will preserve the address (5.2.9p13), meaning the result will be valid.

如果类不是标准布局,则不能依靠这种行为。

If the classes were not standard-layout, you could not rely on this behavior.

这篇关于从对象到第一个成员的reinterpret_cast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆