如果 npos 为 -1,size_type 怎么可能是无符号整数?

How can size_type be an unsigned integral if npos is -1?

如果 std::stringstd::size_type 是默认分配器的

21.3.1 Class template basic_string
typedef typename allocator_traits<Allocator>::size_type size_type;

默认分配器的 std::size_typestd::size_t,

20.9.9 The default allocator
typedef size_t size_type;

而且我们知道std::size_t总是一个无符号整数类型,

C++ Standard
5.3.3 Sizeof
The result of sizeof and sizeof... is a constant of type std::size_t.
[ Note: std::size_t is defined in the standard header <cstddef>

8.2 Types
The contents are the same as the Standard C library header <stddef.h>, with the following changes:


C Standard
6.5.3.4 The sizeof and _Alignof operators
The value of the result of both operators is implementation-defined,
and its type (an unsigned integer type) is size_t, defined in <stddef.h> (and other headers).

std::basic_string::npos(定义为size_type)怎么会是-1?

该定义使用无符号整数遵循模运算这一事实,-1 转换为给定类型的最大无符号整数。

C++ 规范要求有符号类型可以转换为无符号类型。 §4.7/2 指出

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type)

这意味着 C++ 规范保证 -1 可以转换为 size_type,即使 size_type 是无符号的,结果将等于最大可能的 size_type因为向该数字加 1 需要返回 0。