Inside a test, I write a given value to an ostringstream
. After that, I try to evaluate if the correct value was written. However, it seems that the original value I wrote into the stream is changed later on while reading from it.
I reduced my problem to the following code:
#include <sstream>
#include <cassert>
#include <iostream>
int main()
{
std::ostringstream os;
uint16_t data{ 123 };
os.write(reinterpret_cast<const char*>(&data), sizeof(uint16_t));
uint16_t data_returned;
std::string data_str(os.str());
std::copy(data_str.begin(), data_str.end(), &data_returned);
assert(data == 123); // <- not true
assert(data_returned == 123);
}
Here data
seems to be changed (to 0) by std::copy()
.
I also put the code on godbolt: https://godbolt.org/z/bcb4PE
Even more strange, if I change uint16_t data{ 123 };
to const uint16_t data{ 123 };
, everything is fine.
Seems like I am missing some insights on the mechanics of std::copy()
.