Logo

dev-resources.site

for different kinds of informations.

C++20 - s(uper)size

Published at
1/8/2025
Categories
cpp
cpp20
Author
Coral Kashri
Categories
2 categories in total
cpp
open
cpp20
open
C++20 - s(uper)size

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!

Featured ones: