从此代码:

#include <iostream>
#include <typeinfo>
#include <string>

int main() {
    std::string const s = "Thisisastring";
    std::string const ss = "Thisisastringg";
    std::string const sss = "Thisisastrin";
    auto p = ss.find(s);
    std::cout << "p:" << typeid(p).name() << "\np =" << p << std::endl;
    auto pp = sss.find(s);
    std::cout << "pp:" << typeid(pp).name() << "\npp =" << pp << std::endl;
    return 0;
}


我得到以下输出:

p:m
p =0
pp:m
pp =18446744073709551615


问题:


this link中,p应该相对于size_type的类型是m吗?
pp的值是什么意思?溢出了吗?

最佳答案

size_type本身不是类型,它是一个别名,定义如下:

typedef Allocator::size_type size_type; // until c++11
typedef std::allocator_traits<Allocator>::size_type size_type; // since c++11


由于使用的是std::string,因此分配器为std::allocator<char>,因此size_typestd::size_t

std::type_info::name的返回值是实现定义的,而m是编译器(大概是g ++)选择用于std::size_t的返回值。

找不到子字符串时,std::basic_string::find的返回值为std::basic_string::npos,其定义为:

static const size_type npos = -1;


您的情况归结为:

static const std::size_t npos = -1;
// which is (due to arithmetic modulo 2^n):
static const std::size_t npos = std::numeric_limits<std::size_t>::max();


对于编译器,结果值为18446744073709551615,即2^64 - 1,因为std::size_t可能是计算机上的64位值。这是一个可能的值,std::size_t不需要为64位长。

您应该始终直接针对std::basic_string::find测试std::basic_string::npos(和其他相关函数)的返回值。

09-10 00:23
查看更多