C++20 introduced us std::ssize
which stands for signed size. After years of using size_t as a return type from container.size()
function, the understanding that this usage is dangerous had it effect, and now the usage of std::ssize
is considered for the best practice.
The reasoning for that is the following simple iteration example:
for (auto i = container.size() - 1; i >= 0; ++i) { /* do something... */ }
This is unfortunately is an infinite loop, as i
type is unsigned long long
so it'll always be greater than or equals to 0.
Now, let's use the same loop with std::ssize
:
for (auto i = ssize(container) - 1; i >= 0; ++i) { /* do something... */ }
Even if the container is empty, i
would be initialized to -1
and the behavior would be as expected.
If you are still using C++ version lower than 20, you can use: static_cast<int64_t>(container.size())
or to create a wrapper function to do that for you:
template <typename T>
int64_t ssize(const T& container) {
return static_cast<int64_t>(container.size());
}
Good luck!
Top comments (0)