wstringstreams treating -ve values strangely

19 views Asked by At

I am trying to use wstringstreams as a buffer to serialize some data.

The problem I am having is the data gets somehow corrupted. To elaborate the problem, have a look at the following code snippet:

std::vector<long> items;
for (long i = 0; i < 100; ++i)
{
    items.push_back(-1);
}

std::wstringstream ws;
for (auto & val : items)
{
    ws.write((wchar_t *)&val, sizeof(long));
}
auto resultStr = ws.str();

I am expecting at the end the resultStr will have length 100 * sizeof(long). But the size I am getting is 2. What is interesting is that instead of inserting -1 to the items container, if I insert 1 instead, the resultStr is as expected 100 * sizeof(long) big and has the right contents.

With normal stringstreams also I am getting the correct results.

Why is wchar_t based streams messing up the treatment of -ve values?

P.S. I am on Windows 7, vs2015 upadate3 and code compiled and run on x86 debug

0

There are 0 answers