There is no portable way to do this. The implementation is perfectly free to hold onto the buffer, unmodified, after the call to clear()
. If, OTOH, clear()
frees the string's buffer, cstr is now pointing into unallocated memory, but even then it depends on how the memory allocator handles it. A debug allocator will fill the block with some magic number like 0xDEADBEEF, and a production allocator might leave it untouched, or give the entire page back to the OS.
Whichever way you cut it, using the pointer returned by c_str()
after the string has been mutated is undefined behaviour. End of story.