我一定错过了一个明显的事实 - 一段时间没有编程C++.为什么我不能在将c-style字符串分配给const char*变量后打印它?但是,如果我尝试直接打印它而不指定它工作正常:
#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;
}
Run Code Online (Sandbox Code Playgroud)
返回的C字符串c_str仅在std::string获取它的时候可用.一旦std::string被破坏,C字符串也消失了.(此时,尝试使用C String会产生未定义的行为.)
其他操作也可能使C String无效.通常,修改字符串的任何操作都将使返回的指针无效c_str.