Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 511
Pedro d'Aquino Avatar asked Oct 01 '10 19:10

Pedro d'Aquino


People also ask

How does Stringstream C++ work?

The stringstream class in C++ allows a string object to be treated as a stream. It is used to operate on strings. By treating the strings as streams we can perform extraction and insertion operation from/to string just like cin and cout streams.

Does Stringstream allocate?

stringstream is constructed with dummy. This copies the entire string's contents into an internal buffer, which is preallocated.

Can you pass a Stringstream in C++?

Absolutely! Make sure that you pass it by reference, not by value.

Is Stringstream deprecated?

The classes in <strstream> are deprecated. Consider using the classes in <sstream> instead.


1 Answers

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.

like image 110
Steve Townsend Avatar answered Oct 07 '22 02:10

Steve Townsend