简体   繁体   English

我可以在兼容布局的标准布局类型之间合法地reinterpret_cast吗?

[英]Can I legally reinterpret_cast between layout-compatible standard-layout types?

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 class es for filter , flags , etc. with the proper underlying types for the relevant fields. 是“ yes”,是与布局兼容的struct kevent但是将enum class es用于filterflags等,并为相关字段使用适当的基础类型。 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). 它也是标准布局(字段都是private并且它们本身都是标准布局,没有virtual成员,没有基类)。 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". 从对n3690阅读中,我可以确定我的类和struct kevent具有相同的值表示形式,但是我看不到标准中的任何内容,因此无法在它们之间进行reinterpret_cast ,即使这看起来像是对“值表示法”。 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 : 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. EDIT 2014/02/24 16:45 EST :针对评论,我应该澄清一下,我想将reinterpret_cast的第一个类引用到第二个类,因为您当然不能直接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". 但我看不到标准中的任何内容,因此即使它们看起来像是对“值表示”的合理解释,也不允许我在它们之间进行reinterpret_cast Is this technically allowed by the standard? 该标准在技术上允许吗?

No. The standard is clear (see [basic.lval] p10) about which types can be aliased, and layout-compatible types are not included. 否。关于哪些类型可以别名的标准很明确(请参阅[basic.lval] p10),并且不包括与布局兼容的类型。

If not, what does knowing the value representation of a type give you? 如果没有,知道类型的值表示会给您什么?

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 the standard doesn't actually say what can and can't be done with layout-compatible types. AFAICT标准实际上并未说明与布局兼容的类型可以做什么和不能做什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM