String size types.


R. Clayton (rclayton@clayton.cs.monmouth.edu)
(no date)


  What is size_type? Is it a integer?

Exactly what kind of type string::size_type is depends on how the string class
manages memory, but it should be some kind of unsigned integral type. See page
22 of Koenig and Moo.

  Suppose I have a string of length 1 million characters. Will string::length()
  return the correct size?

string::length() always returns the correct size; you probably want to know if
your string can hold a million characters. That depends on how the string
class is implemented. The value you want to look at is string::max_size(),
which is the maximum number of characters a string may contain.

   In my program, I use statements such as

     int i = s.length();

   If s.length() exceeds the size allocated for integer, my program will fail.
   How to avoid these kinds of problems?

Use string::size_type, which is guaranteed to represent a value large enough to
hold any string length. There are also a couple of other reasons why you
should use string::size_type instead of some other type, such as int. First,
size_type is unsigned, and there are subtle and unexpected interactions between
signed and unsigned values, particularly on comparisons; these interactions
lead to difficult to find programming errors. Second, the value string::npos
represents the end-of-string index (similar to the value returned by end() for
stl containers), and comparisons between string::npos and integers almost never
work as correctly.



This archive was generated by hypermail 2.0b3 on Fri Dec 21 2001 - 17:00:04 EST