与const和非成员的联合? [英] An union with a const and a nonconst member?

查看:114
本文介绍了与const和非成员的联合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是未定义的行为

  union A {
int const x;
float y;
};

A a = {0};
a.y = 1;

规格说


在具有静态,线程或自动存储持续时间的const对象占用的存储位置创建一个新对象,或者在这样的const对象在其生命周期结束之前占用的存储位置会导致未定义的行为。 / p>

但是没有编译器警告我,而这很容易诊断错误。

解决方案

最新的C ++ 0x草案标准明确说明了这一点:


在联合中,最多有一个非静态数据成员可以在任何
时间处于活动状态,也就是说,非静态数据成员可以随时将
存储在联合中。


>

  ay = 1; 

很好,因为它会更改活动成员 x y 。如果您随后将 ax 作为右值引用,则该行为将未定义:

  cout < a.x<< endl; //未定义! 

由于您没有创建任何新对象, p>

This appears to be undefined behavior

union A {
  int const x;
  float y;
};

A a = { 0 };
a.y = 1;

The spec says

Creating a new object at the storage location that a const object with static, thread, or automatic storage duration occupies or, at the storage location that such a const object used to occupy before its lifetime ended results in undefined behavior.

But no compiler warns me while it's an easy to diagnose mistake. Am I misinterpreting the wording?

解决方案

The latest C++0x draft standard is explicit about this:

In a union, at most one of the non-static data members can be active at any time, that is, the value of at most one of the non-static data members can be stored in a union at any time.

So your statement

a.y = 1;

is fine, because it changes the active member from x to y. If you subsequently referenced a.x as an rvalue, the behaviour would be undefined:

cout << a.x << endl ; // Undefined!

Your quote from the spec is not relevant here, because you are not creating any new object.

这篇关于与const和非成员的联合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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