I must have missed an obvious fact here — haven’t been programming C++ for a while. Why can’t I print the c-style string after assigning it to a const char* variable? But if I try to print it directly without assigning it works fine:
#include "boost/lexical_cast.hpp"
using namespace std;
using boost::lexical_cast;
int main (int argc, char** argv)
{
int aa=500;
cout << lexical_cast<string>(aa).c_str() << endl; // prints the string "500" fine
const char* bb = lexical_cast<string>(aa).c_str();
cout << bb << endl; // prints nothing
return EXIT_SUCCESS;
}
The C String returned by
c_stris only usable while thestd::stringfrom which it was obtained exists. Once thatstd::stringis destroyed, the C String is gone too. (At that point, attempting to use the C String yields undefined behavior.)Other operations may also invalidate the C String. In general, any operation that modifies the string will invalidate the pointer returned by
c_str.