String :: size_type instead of int

const std::string::size_type cols = greeting.size() + pad * 2 + 2; 

Why string::size_type ? int should work! it contains numbers !!!

+42
c ++ string int
Jul 25 '09 at 3:04
source share
3 answers

Short containment numbers too. Like a signed char.

But none of these types can be large enough to represent the sizes of any rows.

string::size_type guarantees exactly that. This is a type that is large enough to represent the size of the string, regardless of how large the string is.

For a simple example of why this is necessary, consider 64-bit platforms. The int, as a rule, is still 32 bits on them, but you have much more 2 ^ 32 bytes of memory.

So, if an (signed) int was used, you could not create strings larger than 2 ^ 31 characters. size_type will be a 64-bit value on these platforms, so it can represent large strings without problems.

+73
Jul 25 '09 at 3:06
source share

The example you provided is

 const std::string::size_type cols = greeting.size() + pad * 2 + 2; 

from Accelerated C ++ from Koenig . He also sets out the reason for his choice immediately after that, namely:

The type std :: string defines size_type as the name of the corresponding type for storing the number of characters in a string. Whenever we need a local variable to contain the size of the string, we must use std :: string :: size_type as the type of this variable.

The reason we set cols to std :: string :: size_type so that cols can hold the number of characters in the greeting, no matter how big this number is. We could just say that cols is of type int, and indeed, this probably does the job. However, the cols value depends on the size of our input program, and we do not control how long this input can be. It is possible that someone could give our program a string so long that int is not enough to contain its length.

+19
Oct 21 '13 at 5:44
source share

The nested size_type typedef is a requirement for containers compatible with STL (which std::string happens to be), so generic code can choose the right integer type to represent sizes.

It makes no sense to use it in the application code, size_t completely normal (there is no int because it is signed, and you will receive warnings about signing / unsigned).

+7
Jul 25 '09 at 8:51
source share



All Articles