6

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!

AutoBotAM
  • 1,485
  • 3
  • 18
  • 24

1 Answers1

12

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();
ildjarn
  • 62,044
  • 9
  • 127
  • 211
  • 2
    The `const&` looks mighty awkard. Why not just `const std::string mystring(out.str());`? – rubenvb Jun 22 '12 at 23:19
  • 1
    @rubenvb : What do you perceive to be the difference? – ildjarn Jun 23 '12 at 02:21
  • Hi ildjarn. I guess @rubenvb means: When a developer reads `const std::string str(out.str());` he immediately understands that `str` is a copy. But `const std::string& str = out.str();` gives the impression `str` is just a reference to a `string` handled by an other variable. The second case may be confusing, isn't it? – oHo Mar 07 '13 at 08:12
  • @olibre : The second case _is_ just a reference to a temporary... ;-] – ildjarn Mar 07 '13 at 18:15
  • Yep, I asked (yesterday) about [reference to an unnamed temporary object](http://stackoverflow.com/questions/15267676) and I referred to your above answer. (Note: my question is not a duplicate of any other question on SO, the other question is about lifetime of function return object) Now I understand this C++ trick :-) but it was not obvious! Cheers ;-) – oHo Mar 08 '13 at 07:53