std::ostringstream isn't returning a valid str

2019-01-19 19:51发布

问题:

I'm trying to use std::ostringstream to convert a number into a string (char *), but it doesn't seem to be working. Here's the code I have:

#include <windows.h>
#include <sstream>

int main()
{
    std::ostringstream out;
    out << 1234;

    const char *intString = out.str().c_str();

    MessageBox(NULL, intString, intString, MB_OK|MB_ICONEXCLAMATION);

    return 0;
}

The resulting message box simply has no text in it.

This leads me to believe that the call to out.str().c_str() is returning an invalid string, but I'm not sure. Since I've trimmed this program down so far an am still getting the problem, I must have made an embarrassingly simple mistake. Help is appreciated!

回答1:

out.str() returns a std::string by value, which means that you are calling .c_str() on a temporary. Consequently, by the time intString is initialized, it is already pointing at invalid (destroyed) data.

Cache the result of .str() and work with that:

std::string const& str = out.str();
char const* intString = str.c_str();