How does std::stringstream handle wchar_t* in operator<<?

Pedro d&#39;Aquino picture Pedro d'Aquino · Oct 1, 2010 · Viewed 13.6k times · Source

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?

Answer

Steve Townsend picture Steve Townsend · Oct 1, 2010

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.