C++bool获得随机/错误值?
在调试我的代码时,我注意到发生了一些奇怪的事情,所以我添加了更多行并且更加困惑:
#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);将大值转换为int. int是有符号的,它可能给出与上面不执行转换为int.
- How is this the same? I want their sum to be less that 128 not only `node->size`
- @mick basic algebra `a - b - c < d === a < d + b + c`
- I'm a little disappointed and concerned to see at least 2 people agreed with the "How is this the same" comment, when this is basic algebra that is learned in grade-school...