Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

c++ - string::size_type instead of int

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

Why string::size_type? int is supposed to work! it holds numbers!!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A short holds numbers too. As does a signed char.

But none of those types are guaranteed to be large enough to represent the sizes of any strings.

string::size_type guarantees just that. It is a type that is big enough to represent the size of a string, no matter how big that string is.

For a simple example of why this is necessary, consider 64-bit platforms. An int is typically still 32 bit on those, but you have far more than 2^32 bytes of memory.

So if a (signed) int was used, you'd be unable to create strings larger than 2^31 characters. size_type will be a 64-bit value on those platforms however, so it can represent larger strings without a problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...