使用联合时未定义行为的情况
A case of undefined behaviour when using a union
我有以下代码来自"详细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;
}
在那段代码之后,Bartlomiej Filipek先生写道: "然而,虽然上面的代码可能在 C99 中工作,但由于更严格的 alizing 规则,它在 C++ 中是未定义的行为"。
我想更好地理解作者这句话的意思,因为我不明白。 你能详细解释一下吗?
他给出了以下解释(但我需要更多的解释(:
约183...读取与写入时不同类型的工会成员是未定义的。这种双关语是看不见的,或者至少比使用命名的>演员更难发现......
我也不明白这种解释,以及它如何帮助理解上面的代码是未定义的行为。
我将感谢您的深刻解释
这很简单。工会最多有一个活跃成员。当您写入成员时,该成员将变为活动状态。您只能从活动成员读取。
例:
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++时未定义的引用
- vscode g++链路故障:体系结构x86_64的未定义符号
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 不知道某个东西是否被忽略会引入未定义的行为吗
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 未定义的引用在哪里
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 对Py_Initialize()的未定义引用
- c++11评估顺序(未定义的行为)
- 如果未定义的C++行为符合 C 定义的行为,会发生什么情况?
- 未定义的参考C ,不寻常的情况
- 我如何在不将所有相关代码带到标头的情况下解决模板成员函数的未定义引用
- 未分配返回未定义对象类型引用的 C++ 函数的返回值时会发生什么情况
- 为什么在包含类头的情况下,我的数组在main中未定义
- 这是一种未定义的行为吗?我可以在没有温度的情况下交换值吗?
- 在启用 SSL 的情况下构建 libircclient 时对 'DLopen' 的未定义引用
- 在对象文件中具有未定义符号类型的程序如何在没有任何链接器错误的情况下进行编译"U"?
- 在溢出的情况下,i++是否对小于int的有符号类型调用未定义的行为?
- 对Logger::getInstance()的未定义引用-但仅在某些情况下