保存ostringreader.str().c_str()

Civ*_*ing 1 c++ ostringstream

为什么在这段代码中读出y之后text1的值会发生变化?

void func()
{
    int value1 = 5;
    double value2 = 1.5;
    std::ostringstream x, y;

    x << value1;
    y << value2;


    const char *text1 = x.str().c_str();
    fprintf(stderr, "text1: v=%s, p=%p\n", text1, &text1);
    const char *text2 = y.str().c_str();
    fprintf(stderr, "text1: v=%s, p=%p\ntext2: v=%s, p=%p\n", text1, &text1, text2, &text2);
}
Run Code Online (Sandbox Code Playgroud)

输出:

text1:v = 5,a = 0xbfcfd508

text1:v = 1.5,a = 0xbfcfd508

text2:v = 1.5,a = 0xbfcfd510

Kon*_*lph 7

在评估str().c_str()表达式之后,将释放std::string由调用创建的临时实例,str()并且char指针指向Nirvana.你需要存储返回值str()!

  • [c_str](http://www.cplusplus.com/reference/string/string/c_str/)的返回值仅保证在对象上的下一个非const操作之前有效.析构函数是非常量的.因此,您在使用之前存储的结果将变为无效. (2认同)