通过工会未定义行为const的铸造? [英] Is const-casting via a union undefined behaviour?

查看:117
本文介绍了通过工会未定义行为const的铸造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不像C ++,C没有任何的的const_cast 概念。也就是说,有一个const限定指针转换为不合格的指针没有有效的方式:

Unlike C++, C has no notion of a const_cast. That is, there is no valid way to convert a const-qualified pointer to an unqualified pointer:

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

第一关:这是投居然不确定的行为

First off: Is this cast actually undefined behaviour?

在任何情况下,海湾合作委员会警告说这件事。为了使干净code,需要一个const铸(即在那里我可以保证,我不会变异的内容,但我已经是一个可变的指针),我已经看到了下面的转换的技巧:

In any event, GCC warns about this. To make "clean" code that requires a const-cast (i.e. where I can guarantee that I won't mutate the contents, but all I have is a mutable pointer), I have seen the following "conversion" trick:

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

用法: u.cp = P; Q = u.mp;

什么是通过这样的结合虚掷常量性C语言的规则?我的C知识只是很零散,但我听说C是远远宽松些比C ++联合访问,所以虽然我对这个建筑有不好的预感,我想从标准的参数(C99我想,但如果这在C11改变了这将是很好的了解)。

What are the C language rules on casting away constness through such a union? My knowledge of C is only very patchy, but I've heard that C is far more lenient about union access than C++, so while I have a bad feeling about this construction, I would like an argument from the standard (C99 I suppose, though if this has changed in C11 it'll be good to know).

推荐答案

这是实现定义,见C99 6.5.2.3/5:

It's implementation defined, see 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评论说,这可能是明确毕竟

Update: @AaronMcDaid commented that this might be well-defined after all.

规定的标准以下6.2.5 / 27:

The standard specified the following 6.2.5/27:

同样,指针的兼容合格的或不合格的版本
  类型应具有相同的重presentation和对齐
  requirements.27)

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

27)同样进行再presentation和对齐要求是为了
  暗示互换性作为函数的参数,从返回值
  功能,和工会的成员。

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):

And (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.

一个的可能的结论是,的在这种特殊情况下的,只有整整一个访问在工会中的元素的方式房间。

One might conclude that, in this particular case, there is only room for exactly one way to access the elements in the union.

这篇关于通过工会未定义行为const的铸造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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