Originally Posted by
CornedBee
2) ss.str().c_str() will work, but only as long as the temporary std::string stays alive.
This is true, but the constraint is more general than that. The string itself needs to remain unmodified. So
Code:
std::string some_string(some_content);
const char *p = some_string.c_str();
// some operation that modifies the content of some_string()
strcpy(some_buffer, p); // undefined behaviour as p is effectively a dangling reference
ss.str() yields a temporary string with limited lifetime, and ss.str().c_str() is only valid as long as that temporary remains alive. Being destructed, so it is no longer alive, is a rather significant modification of that temporary string.
Originally Posted by
CornedBee
Which is long enough to pass the c-string to a function (like strcpy), but not more than that.
The other obvious caveat is that the c_str() method returns a const pointer, which is a fairly broad hint you're not supposed to modify the data it points at. So
Code:
char x[10];
strcpy(x, ss.str.c_str());
is OK (as long as the length of the string with terminating zero does not exceed 9) but this;
Code:
char x[] = "Hello";
strcpy(ss.str.c_str(), x);
will not work; the compiler will complain bitterly as the first argument of strcpy() is required to be non-const.