gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:34:47 26 4
gpt4 key购买 nike

如果std::size_typestd::string是默认分配器的,

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

还有 std::size_type默认分配器是 std::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?

最佳答案

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。

关于c++ - 如果 npos 为 -1,size_type 怎么可能是无符号整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36991202/

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