Mail Archives: djgpp/1999/12/25/21:24:33
Andrew R. Gillett <arganoid AT fatal-design DOT com> wrote:
>I don't know exactly how c_str() works - does the char array created by
>it continue to exist after the line on which it is called?
Not reliably. To quote Stroustrup, "The user cannot rely on its value after
a subsequent call on a non-const function on the string." He is talking about
data(), but the next sentence states c_str is like data, but adds the zero
terminator.
(C++ Programming Language 3rd Ed pg 589)
Also, the preferred method to get the string into a buffer is the copy() member
of the basic_string class, if you're a C++ purist. Of course, if you're a
purist, you probably are using the C++ interface rather than the C version.
One possible pitfall is C++ strings may contain embedded '\0' characters, since
the length is of the string is stored separately, and does not depend on the
'\0' terminator. The entire string will be correctly copied to a buffer, but
the C style functions will not see anything past the first '\0'.
Also, it is possible to derive classes from basic_string that will not act as
expected if converted to C style and handled with the usual calls. C is not
always graceful if naive assumptions are made when handling
internationalization.
- Raw text -