我可以在布局兼容的标准布局类型之间合法reinterpret_cast? [英] Can I legally reinterpret_cast between layout-compatible standard-layout types?

查看:181
本文介绍了我可以在布局兼容的标准布局类型之间合法reinterpret_cast?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个类,假设枚举类型布局是否与其底层类型兼容?是yes,与布局兼容 struct kevent 但使用枚举类用于过滤器 flags 等,它也是标准布局(字段都是私人和所有自己的标准布局,没有虚拟成员,没有基类)。从我的读取 n3690 ,我可以确定我的类和 struct kevent 具有相同的值表示,但我可以看不到标准中的任何东西,因此允许我<@ c $ c> reinterpret_cast 之间,即使这似乎是值表示的合理解释。这是技术上允许的标准吗?如果不是,知道类型的值表示是什么给你?

I'm writing a class that, assuming the answer to Are enumeration types layout compatible with their underlying type? is "yes", is layout-compatible struct kevent but uses enum classes for filter, flags, etc. with the proper underlying types for the relevant fields. It is also standard-layout (the fields are all private and all themselves standard layout, there are no virtual members, there are no base classes). From my reading of n3690, I can determine that my class and struct kevent have the same value representation, but I can't see anything in the standard that therefore allows me to reinterpret_cast between them, even though that seems like the reasonable interpretation of "value representation". Is this technically allowed by the standard? If not, what does knowing the value representation of a type give you?

EDIT 2014/02/24 16:45 EST :回应对于注释,我应该澄清,我想要 reinterpret_cast 第一个类到第二个的引用,当然你不能直接 reinterpret_cast 非指针类型为另一个非指针类型。

EDIT 2014/02/24 16:45 EST: In response to a comment, I should clarify that I want to reinterpret_cast the first class to a reference to the second, as of course you can't directly reinterpret_cast a non-pointer type to another non-pointer type.

推荐答案


但我看不到标准中的任何内容,因此允许我<@ c $ c> reinterpret_cast 之间,即使这似乎是值表示。这是标准技术上允许的吗?

but I can't see anything in the standard that therefore allows me to reinterpret_cast between them, even though that seems like the reasonable interpretation of "value representation". Is this technically allowed by the standard?

否。标准是清楚的(见[basic.lval] p10)关于哪些类型可以别名,并且不包括布局兼容类型。

No. The standard is clear (see [basic.lval] p10) about which types can be aliased, and layout-compatible types are not included.


如果没有,知道类型的值表示是什么给你?

If not, what does knowing the value representation of a type give you?

如果类型都是可以复制的,值表示,那么你可以从一个类型的对象到另一个类型的对象的memcpy,反之亦然。如果他们不是普通的可复制,那么它根本不会给你太多。

If the types are both trivially copyable and have the same value representation then you could memcpy from an object of one type to an object of the other type, and vice versa. If they're not trivially copyable then it doesn't give you much at all.

AFAICT标准并没有说明什么可以做和不能做布局兼容类型。

AFAICT the standard doesn't actually say what can and can't be done with layout-compatible types.

这篇关于我可以在布局兼容的标准布局类型之间合法reinterpret_cast?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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