简体   繁体   English

std :: stringstream如何在operator <<中处理wchar_t *?

[英]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). 但它确实(至少在VC ++上)。 I'm guessing this is due to the following ostream::operator<< overload: 我猜这是由于以下ostream::operator<< overload:

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

Does this have the potential to silently break my code, if I inadvertently mix character types? 如果我无意中混合了字符类型,这是否有可能默默地破坏我的代码?

Yes - you need wstringstream for wchar_t output. 是的 - wchar_t输出需要wstringstream

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. 如果你尝试将const wstring&传递给stringstream ,它将无法编译,正如你所指出的那样。

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. 您将只看到指针值的表示而不是字符串,因此它不是潜在的崩溃或未定义的行为,只是输出不是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM