Boost 仅序列化 std::wstring 的第一个字符

发布于 2024-10-31 12:27:48 字数 386 浏览 0 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尐籹人 2024-11-07 12:27:48

您正在尝试使用窄字符存档序列化宽字符串。这会导致包含宽字符串的字节序列被解释为窄字符序列。如果考虑到 ASCII 字符仅占用相应宽字符编码的一个字节,而将宽字符集的所有其他字节保留为零,那么很明显,窄字符存档在看到第一个字符后就会停止(因为它击中了 ASCII 字符代码后面的零字节)。

如果您将代码更改为:

std::wstring text;

template<class Archive> 
void serialize(Archive &ar, const unsigned int version)
{ 
    ar & text; 
}

std::wstringstream stream;
boost::archive::text_woarchive archive(stream);
archive << params;

它将按预期工作。

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:

std::wstring text;

template<class Archive> 
void serialize(Archive &ar, const unsigned int version)
{ 
    ar & text; 
}

std::wstringstream stream;
boost::archive::text_woarchive archive(stream);
archive << params;

it will work as expected.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文