[英]Negative size_t
Is it well-specified (for unsigned types in general), that: 是否已明确指定(通常适用于无符号类型):
static_assert(-std::size_t{1} == ~std::size_t{0}, "!");
I just looked into libstdc++ 's std::align
implementation and note using std::size_t
negation: 我只是研究了libstdc ++的
std::align
实现,并使用std::size_t
否定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);
}
}
Unsigned integer types are defined to wrap around, and the highest possible value representable in an unsigned integer type is the number with all bits set to one - so yes. 无符号整数类型被定义为环绕,并且无符号整数类型中可表示的最大可能值是所有位都设置为1的数字-可以。
As cpp-reference states it ( arithmetic operators / overflow ): 正如cpp-reference指出的那样( 算术运算符/溢出 ):
Unsigned integer arithmetic is always performed modulo 2 n where n is the number of bits in that particular integer.
无符号整数算术始终以2 n为模执行,其中n是该特定整数中的位数。 Eg for
unsigned int
, adding one toUINT_MAX
gives0
, and subtracting one from0
givesUINT_MAX
.例如,对于
unsigned int
,在UINT_MAX
加1得到0
,从0
减去1得到UINT_MAX
。
Related: Is it safe to use negative integers with size_t? 相关: 在size_t中使用负整数是否安全?
Is it well-specified (for unsigned types in general), that:
是否已明确指定(通常适用于无符号类型):
static_assert(-std::size_t{1} == ~std::size_t{0}, "!");
No, it is not. 不它不是。
For calculations using unsigned types, the assertion must hold. 对于使用无符号类型的计算,断言必须成立。 However, this assertion is not guaranteed to use unsigned types.
但是,不能保证此断言使用无符号类型。 Unsigned types narrower than
int
would be promoted to signed int
or unsigned int
(depending on the types' ranges) before -
or ~
is applied. 小于
int
无符号类型将在应用-
或~
之前提升为signed int
或unsigned int
(取决于类型的范围)。 If it is promoted to signed int
, and signed int
does not use two's complement for representing negative values, the assertion can fail. 如果将其提升为
signed int
,并且signed int
不使用二进制补码表示负值,则断言可能会失败。
libstdc++'s code, as shown, does not perform any arithmetic in any unsigned type narrower than int
though. 如图所示,libstdc ++的代码不会在比
int
窄的任何无符号类型中执行任何算术运算。 The 1u
in __aligned
ensures each of the calculations use unsigned int
or size_t
, whichever is larger. 的
1u
在__aligned
确保每个计算的使用unsigned int
或size_t
,任一较大。 This applies even to the subtraction in __space -= __diff
. 这甚至适用于
__space -= __diff
的减法。
Unsigned types at least as wide as unsigned int
do not undergo integer promotions, so arithmetic and logical operations on them is applied in their own type, for which Johan Lundberg's answer applies: that's specified to be performed modulo 2 N . 至少与
unsigned int
一样宽的无符号类型不会进行整数提升,因此对它们的算术和逻辑运算将以其自己的类型应用,Johan Lundberg的答案适用于此:指定以2 N模执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.