C++ bool 获取 random/wrong 值?

C++ bool gets random/wrong value?

在调试我的代码时,我注意到发生了一些奇怪的事情,所以我添加了更多行并且更加困惑:

#include <iostream>
#include <memory>

struct Node
{
    size_t size = 0;
};

class MallocMetadata {
public:
    size_t size; /** Effective allocation - requested size **/
    bool is_free;
    MallocMetadata *next;
    MallocMetadata *prev;
    MallocMetadata *next_free;
    MallocMetadata *prev_free;
};

int main()
{
    size_t size = 0;
    auto node = std::make_shared<Node>();
    int tmp_res=node->size - size - sizeof(MallocMetadata);
    bool test=(node->size - size - sizeof(MallocMetadata)) < 128;
    bool test1=tmp_res<128;
    std::cout << tmp_res << "\n";
    std::cout << test << "\n";
    std::cout << test1 << "\n";
}

在 运行 我看到的这 3 行之后:

tmp_res=-48
test = false
test1 = true

这怎么可能!为什么 test 为假,-48 小于 128

证明如下:

看起来 node->size - size - sizeof(MallocMetadata) 部分是用无符号整数计算的。

当无符号整数的计算结果为负数时,该类型的最大数加一,结果回绕

因此,该值看起来像是一个大值(128 或更多),使得表达式 (node->size - size - sizeof(MallocMetadata)) < 128 为假。

另一方面,int tmp_res=node->size - size - sizeof(MallocMetadata);会将大值转换为intint 已签名,它可能给出与上面不执行转换为 int.

的表达式不同的值

我相信只要表达式中有无符号值,结果也往往是无符号的。

size_t size = 0;
auto val = 1 + 100 + (-100) + size;
std::cout << typeid(val).name();

'val' 也将是 size_t。因此,在您的情况下,您试图在 size_t 中存储一个负值,这会导致溢出。 您可以将其显式转换为带符号的整数,如果我不是 mistaken.Like 那么这就足够了,所以:

bool test=int(node->size - size - sizeof(MallocMetadata)) < 128;