Boost 仅序列化 std::wstring 的第一个字符
我正在使用 boost 来序列化文本存档 std::wstring 变量。如果我切换到 std::string 它工作得很好,但是当我使用 wstring 时我只序列化了一个字符。为什么?
std::wstring text;
template<class Archive> void serialize(Archive &ar, const unsigned int version)
{
ar & text;
}
...
std::ostringstream stream;
boost::archive::text_oarchive archive(stream);
archive << params;
...
stream.str()
I'm using boost to serialize with the text archive an std::wstring variable. If I switch to std::string it works very well but when I use wstring I get only one character serialized. Why?
std::wstring text;
template<class Archive> void serialize(Archive &ar, const unsigned int version)
{
ar & text;
}
...
std::ostringstream stream;
boost::archive::text_oarchive archive(stream);
archive << params;
...
stream.str()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在尝试使用窄字符存档序列化宽字符串。这会导致包含宽字符串的字节序列被解释为窄字符序列。如果考虑到 ASCII 字符仅占用相应宽字符编码的一个字节,而将宽字符集的所有其他字节保留为零,那么很明显,窄字符存档在看到第一个字符后就会停止(因为它击中了 ASCII 字符代码后面的零字节)。
如果您将代码更改为:
它将按预期工作。
You are trying to serialize a wide character string with a narrow character archive. This causes the byte sequence comprising your wide character string to be interpreted as a sequence of narrow characters. If you take into account that ASCII characters take up only one of the bytes of the corresponding wide character encoding, leaving all other bytes of the wide character set to zero, it gets obvious, that the narrow character archive stops after seeing the first character (as it hits the zero byte(s) following the ASCII character code).
If you change your code to:
it will work as expected.