gpt4 book ai didi

c - const-casting 是通过 union 未定义的行为吗?

转载 作者:太空狗 更新时间:2023-10-29 16:31:04 27 4
gpt4 key购买 nike

与 C++ 不同,C 没有 const_cast 的概念。也就是说,没有将 const 限定指针转换为非限定指针的有效方法:

void const * p;
void * q = p; // not good

首先:这个转换实际上是未定义的行为吗?

无论如何,GCC 都会对此发出警告。为了制作需要 const-cast 的“干净”代码(即我可以保证我不会改变内容,但我所拥有的只是一个可变指针),我看到了以下“转换”技巧:

typedef union constcaster_
{
void * mp;
void const * cp;
} constcaster;

用法:u.cp = p; q = u.mp;.

C 语言关于通过 union 放弃常量的规则是什么?我对 C 的了解非常零散,但我听说 C 在 union 访问方面比 C++ 宽松得多,所以虽然我对这种结构有不好的感觉,但我想从标准(我想是 C99,不过,如果这在 C11 中有所改变,那将是一件好事。

最佳答案

它是实现定义的,参见 C99 6.5.2.3/5:

if the value of a member of a union object is used when the most recent store to the object was to a different member, the behavior is implementation-defined.

更新:@AaronMcDaid 评论说这毕竟可能是明确定义的。

标准规定了以下 6.2.5/27:

Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements.27)

27) The same representation and alignment requirements are meant to imply interchangeability as arguments to functions, return values from functions, and members of unions.

和 (6.7.2.1/14):

A pointer to a union object, suitably converted, points to each of its members (or if a member is a bitfield, then to the unit in which it resides), and vice versa.

有人可能得出结论,在这种特殊情况下,只有一种方法可以访问 union 中的元素。

关于c - const-casting 是通过 union 未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8836418/

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