gpt4 book ai didi

c++ - 匿名 union 是否可以接受用于别名结构中的成员变量?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:27:16 27 4
gpt4 key购买 nike

假设我有以下 C++ 代码:

struct something
{
// ...
union { int size, length; };
// ...
};

这将创建 struct 的两个成员,它们访问相同的值:sizelength

将两个成员视为完整的别名(即设置大小,然后访问长度,反之亦然)是否是未定义的行为?是否有“更好”的方式来实现此类行为,或者这是一种可接受的实现方式?

最佳答案

是的,这是允许的并且定义明确。根据 §3.10 [basic.lval]:

10/ If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:

— the dynamic type of the object

[...]

因为这里我们存储了一个 int 并读取了一个 int,所以我们通过与对象具有相同动态类型的泛左值访问该对象,因此一切都很好。


对于共享相同前缀的结构,标准中甚至有一个特殊警告。或者,在标准语言中,标准布局类型共享一个公共(public)初始序列

§9.2/18 If a standard-layout union contains two or more standard-layout structs that share a common initial sequence, and if the standard-layout union object currently contains one of these standard-layout structs, it is permitted to inspect the common initial part of any of them. Two standard-layout structs share a common initial sequence if corresponding members have layout-compatible types and either neither member is a bit-field or both are bit-fields with the same width for a sequence of one or more initial members.

即:

struct A { unsigned size; char type; };
struct B { unsigned length; unsigned capacity; };

union { A a; B b; } x;

assert(x.a.size == x.b.length);

编辑:鉴于 int 不是 struct(也不是 class),恐怕它实际上是没有正式定义(我当然看不到标准中的任何内容),但在实践中应该是安全的……我已经把这些问题带到了 isocpp 论坛;你可能找到了一个洞。

编辑:在上述讨论之后,我看到了 §3.10/10。

关于c++ - 匿名 union 是否可以接受用于别名结构中的成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15277819/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com