gpt4 book ai didi

c++ - 具有 const 和 nonconst 成员的 union ?

转载 作者:IT老高 更新时间:2023-10-28 21:48:12 29 4
gpt4 key购买 nike

这似乎是未定义的行为

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

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

规范说

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.

但是没有编译器会警告我,因为它很容易诊断错误。我是否误解了措辞?

最佳答案

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

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.

所以你的陈述

a.y = 1;

很好,因为它将事件成员从 x 更改为 y。如果您随后将 a.x 引用为右值,则行为将是未定义的:

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

您对规范的引用与此处无关,因为您没有创建任何新对象。

关于c++ - 具有 const 和 nonconst 成员的 union ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5653471/

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