Is there any benefit to using std::string::size_type over size_t?

3.7k views Asked by At

I'm reviewing another developer's code, which contains the following:

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

I'm arguing that using size_t would be easier to understand and just as safe, since the STL standard states that std::string is std::basic_string<char, std::allocator>, and std::allocator::size_type is size_t.

He wants assurance that that the STL standard couldn't possibly ever change to make this assumption invalid; if the standard could change, then size_type would be safer than size_t.

Could that happen? Is there any other reason to use size_type rather than size_t?

2

There are 2 answers

0
Fred Foo On BEST ANSWER

size_type should be used in code templated on the container type. When the code you have always operates on std::string, you can just use size_t.

11
Seth Carnegie On

I think the best way would be to use auto and that way you can automatically conform to whatever the function returns:

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

It avoids the problem you're describing and it's a lot shorter.

As larsmans mentions in the comments, you may be wanting to store string indices in a struct or whatever without having a variable available to get the return type from. That's doable too:

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

But more complicated and not shorter than std::string::size_type though. So for storing things, you probably would want to use the type's size_type, but for local variables and stuff, use auto.