gpt4 book ai didi

C++ 引发溢出

转载 作者:搜寻专家 更新时间:2023-10-31 01:31:03 24 4
gpt4 key购买 nike

为了读取位组,我自己写了一个小函数,它读取一个位组并返回值。其实我以为附加示例应导致以下命令溢出

(BitGroupMask << BitGroupPosition)

根据标准,中间结果被解释为整数。但是,结果对于所有测试值都是正确的。显然,编译器会检查整个 Expression 中最大的数据类型。至少,我猜。

我的问题:行为取决于编译器还是在 C++ 标准中定义?

代码:

#include <iostream>
#include <bitset>


using namespace std;


uint64_t Variable{0b1011111111111111111111111111111111111111111111111111111111111111ULL};
uint8_t GMask{0b1111};
uint8_t GPos{60};


template <typename VarType, typename MaskType>
inline VarType readBitGroup(VarType Var, MaskType BitGroupMask, MaskType BitGroupPosition)
{
//return (VarType)((Var & ((VarType)BitGroupMask << BitGroupPosition)) >> BitGroupPosition);
return ((Var & (BitGroupMask << BitGroupPosition)) >> BitGroupPosition);
}


int main()
{
cout << std::bitset<64>(Variable) << std::endl;
cout << std::bitset<4>(readBitGroup(Variable, GMask, GPos)) << std::endl;
return 0;
}

最佳答案

有问题的代码是

uint8_t GMask{0b1111};
uint8_t GPos{60};
... (GMask << GPos) ...

如果我正确阅读了标准

The operands shall be of integral or unscoped enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand. The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand.

您的 uint_8 操作数被提升,然后发生移位。

A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank (7.15) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned int.

第二个引号指定将值提升为 int - 因为它足够大以表示值 15 和 60。

然后 - 回到第一个引用我们看到行为未定义

因此,您有责任将移位的左操作数转换为足以存储移位结果的类型。

关于C++ 引发溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46468976/

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