gpt4 book ai didi

c++ - 负尺寸_t

转载 作者:行者123 更新时间:2023-11-30 01:38:10 24 4
gpt4 key购买 nike

是否明确规定(对于一般的无符号类型),即:

static_assert(-std::size_t{1} == ~std::size_t{0}, "!");

我刚刚研究了 libstdc++std::align 实现并注意使用 std::size_t 取反:

inline void*
align(size_t __align, size_t __size, void*& __ptr, size_t& __space) noexcept
{
const auto __intptr = reinterpret_cast<uintptr_t>(__ptr);
const auto __aligned = (__intptr - 1u + __align) & -__align;
const auto __diff = __aligned - __intptr;
if ((__size + __diff) > __space)
return nullptr;
else
{
__space -= __diff;
return __ptr = reinterpret_cast<void*>(__aligned);
}
}

最佳答案

无符号整数类型被定义为环绕,无符号整数类型中可表示的最大可能值是所有位都设置为 1 的数字 - 所以是的。

如 cpp-reference 所述(arithmetic operators / overflow):

Unsigned integer arithmetic is always performed modulo 2n where n is the number of bits in that particular integer. E.g. for unsigned int, adding one to UINT_MAX gives ​0​, and subtracting one from 0​ gives UINT_MAX.

相关:Is it safe to use negative integers with size_t?

关于c++ - 负尺寸_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48490710/

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