Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost serialize only first character of std::wstring

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()
like image 255
Stefano Avatar asked Dec 27 '22 22:12

Stefano


1 Answers

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.

like image 127
hkaiser Avatar answered Jan 05 '23 17:01

hkaiser