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?
If I need to get a NUL-terminated char array out of a std::string in
Share
The standard says that calling
c_str()may invalidate references, pointers, and interators referring to the elements of thestring, 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).