The const at the end says โthis function will not change the stringโ. This is a slightly different use of the const keyword than we have seen before when declaring constants. But it gets at the same idea. This const at the end of the prototype guarantees that if you call fruit.size(), the string fruit will not be modified.
The return type - size_type - is new. It would be reasonable to expect size() to return an int. We expect size to be a value like 0 or 6 or 3234. So why doesnโt it? The short version is that we never expect the size to be negative and the exact size maximum size of an int variable is not always the same from one platform to another. You should think of size_type as a type that is guaranteed to be able to hold the size of any possible string and can only hold 0 or positive numbers.
To store a size_type we will use a variable of type size_t. This is a bit of a simplification (see Noteย 9.5.2). But it will serve our needs just fine. You can use a size_t just like an int. You can do math with them, compare them to other numbers, etc... The only difference is that they can never hold a negative value. Trying to assign one will result in the value โwrapping aroundโ and becoming a large positive one:
Any code that needs to talk about the size of a string, or the position of some character(s) in a string, will always use size_t. Because size_t is not that different than an int (other than not being unsigned and possibly having a different max value), you may be able to use int values anywhere a size_t is expected. But the compiler may give you a doing soโit knows there are subtle differences that may cause issues.
Although you should try to use size_t when working with the size of strings or locations in strings, there may be times when you want to take something like the size and store it into an int. To do so, you just need to cast the value into an int:
size_t is technically different than the size_type defined in string, which has the full name of string::size_type. However, string::size_type is usually defined as being the same as size_t. And size_t is often defined as being the same as uint64_t (see Subsectionย 4.6.2 for unit64_t). So why have three different names for what all end up as the same type? Flexibility. It does not HAVE to be the case that string::size_type is always a 64-bit unsigned integer. On some computing platforms a different value might make more sense.