9

Given that the following snippet doesn't compile:

std::stringstream ss;
ss << std::wstring(L"abc");

I didn't think this one would, either:

std::stringstream ss;
ss << L"abc";

But it does (on VC++ at least). I'm guessing this is due to the following ostream::operator<< overload:

ostream& operator<< (const void* val );

Does this have the potential to silently break my code, if I inadvertently mix character types?

Pedro d'Aquino
  • 5,130
  • 6
  • 36
  • 46
  • 2
    Are you intentionally using `stringstream` instead of `wstringstream`? – dgnorton Oct 01 '10 at 19:54
  • No, it's actually the other way around. I'm using `wstringstream` all the time and sometimes forget to add `L` before the string, especially when writing log messages. – Pedro d'Aquino Oct 04 '10 at 13:02

2 Answers2

14

Yes - you need wstringstream for wchar_t output.

You can mitigate this by not using string literals. If you try to pass const wstring& to stringstream it won't compile, as you noted.

Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
6

Does this have the potential to silently break my code, if I inadvertently mix character types?

In a word: yes, and there is no workaround that I know of. You'll just see a representation of a pointer value instead of a string of characters, so it's not a potential crash or undefined behaviour, just output that isn't what you want.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656