gpt4 book ai didi

c++ - 使用 union 时出现未定义行为的情况

转载 作者:行者123 更新时间:2023-12-01 23:01:50 24 4
gpt4 key购买 nike

我有以下代码来自《C++17 详细》一书:

union Superfloat{
float f;
int i;
}

int RawMantissa(Superfloat f){
return f.i & ((1< 23) -1);
}

int RawExponent(Superfloat f){
return (f.i >> 23)& 0xFF;
}

在该代码之后,Bartlomej Filipek 先生写道:“然而,虽然上面的代码可能在 C99 中工作,但由于更严格的 alising 规则,它在 C++ 中是未定义的行为”。

我想更好地理解作者这句话的意思,因为我不明白。能详细解释一下吗?

他给出了以下解释(但我需要更多解释):

C.183!... it is undefined to read a union member with a different type from the one with which it was written. Such punning is invisible, or at least harder to spot than using a named >cast.....

我也不明白这个解释,也不明白它如何帮助理解上面的代码是未定义的行为。

非常感谢您的深入解释

最佳答案

这非常简单。一个 union 最多有一名活跃成员。当您向某个成员写入内容时,该成员就会变得活跃。您只能阅读活跃成员(member)的信息。

示例:

union U
{
float f;
int i;
};

auto foo_1()
{
U u; // no member is active

u.f = 24.5; // write to `u.f` . `u.f` is now the active member

int i = u.i; // read of `u.i` Since `u.i` is not the active member this is UB in C++
}
auto foo_2()
{
U u;
// no active member

u.f = 24.5; // write to `u.f` . `u.f` is now the active member

float f = u.f; // read of `u.f` . Ok since `u.f` is the active member

u.i = 11; // write to `u.i` . `u.i` is now the active member.
// `u.f` is NOT the active member anymore

int i = u.i; // ok, read of the active member `u.i`

float f2 = u.f; // read of `u.f`. UB, since `u.f` is not the active member
}

关于c++ - 使用 union 时出现未定义行为的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59238703/

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