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

时间:2012-05-09 16:17:26

标签: c++ stl size-type

我正在审核其他开发人员的代码,其中包含以下内容:

std::string name;
...
std::string::size_type colon = name.find(":");

我认为使用size_t会更容易理解并且同样安全,因为STL标准规定std::stringstd::basic_string<char, std::allocator>,而std::allocator::size_type是{ {1}}。

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

会发生这种情况吗?是否有其他理由使用size_t而不是size_type

2 个答案:

答案 0 :(得分:8)

应在容器类型模板化的代码中使用

size_type。如果您始终在std::string上运行代码,则可以使用size_t

答案 1 :(得分:6)

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

auto colon = name.find(":");

它避免了您所描述的问题,并且缩短了很多。

正如larsmans在评论中提到的那样,您可能希望将字符串索引存储在struct或其他任何内容中,而无需使用变量来获取返回类型。这也是可行的:

struct StoreStringIndex {
    decltype(declval<std::string>().length()) length;
};

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