If I need to get a NUL-terminated char
array out of a std::string
in a situation where I need to be sure nothing will be allocated, is it safe to use c_str
to do so? For example, if I'm inside a destructor and I want to copy some data from a string
into a pre-allocated, fixed-size buffer, can I use c_str
and be sure it won't throw anything?
The standard says that calling c_str()
may invalidate references, pointers, and interators referring to the elements of the string
, which implies that reallaocation is permitted (21.3/5 "Class template basic_string").
You might want to just call string::copy()
to get your copy (you'll need to add the null terminator yourself if you need it).
No, the standard gives no such guarantee. The only guarantee in the C++ standard is that the returned value points to a char
array with the same contents as the std::string
, plus a nul-terminator.
So it would be standards-conforming for an implementation to store its internal representation in some way other than a C-string, and allocate a C-string on the fly when you call c_str
, although I'm fairly certain that no widely used STL implementation actually does this.
Now, with respect to C++0x, I have heard (although I am at a loss for finding documentation for this at the moment), that one of the changes is going to be to require that std::string
operate on contiguous storage (a similar requirement already exists for std::vector
). So in that case, you could access the span from &str[0]
through &str[0]+str.length()-1
as if it were a C-string without a nul-terminator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With