使用std :: string :: size_type比size_t有什么好处吗?

Cho*_*ett 3 c++ stl size-type

我正在审查另一个开发人员的代码,其中包含以下内容:

std::string name;
...
std::string::size_type colon = name.find(":");
Run Code Online (Sandbox Code Playgroud)

我争辩说,使用size_t会更容易理解和同样安全,因为STL标准规定std::stringstd::basic_string<char, std::allocator>,并且std::allocator::size_typesize_t.

他希望保证STL标准不可能改变以使这个假设无效; 如果标准可以改变,那么size_type会更安全size_t.

这会发生吗?有没有其他理由可以使用size_type而不是size_t

Fre*_*Foo 8

size_type应该在容器类型模板化的代码中使用.当您始终操作的代码时std::string,您可以使用size_t.


Set*_*gie 6

我认为最好的方法是使用auto,这样你就可以自动地符合函数返回的任何内容:

auto colon = name.find(":");
Run Code Online (Sandbox Code Playgroud)

它避免了你描述的问题而且它缩短了很多.

正如larsmans在评论中提到的那样,你可能想要将字符串索引存储在一个struct或者任何东西中,而没有可用的变量来获取返回类型.这也是可行的:

struct StoreStringIndex {
    decltype(declval<std::string>().length()) length;
};
Run Code Online (Sandbox Code Playgroud)

但比较复杂而且不短std::string::size_type.因此,对于存储内容,您可能希望使用类型size_type,但对于局部变量和内容,请使用auto.