Getting different output in following cases
std::string temp, temp1 = "foo", temp2 = "bar";
std::vector<char> test;
std::ostringstream s;
s << temp1;
temp = s.str();
std::copy(s.str().begin(), s.str().end(), std::back_inserter(test));
std::copy(temp2.begin(), temp2.end(), std::back_inserter(test));
std::cout << &test[0];
Output : foo
std::string temp, temp1 = "foo", temp2 = "bar";
std::vector<char> test;
std::ostringstream s;
s << temp1;
temp = s.str();
std::copy(temp.begin(), temp.end(), std::back_inserter(test));
std::copy(temp2.begin(), temp2.end(), std::back_inserter(test));
std::cout << &test[0];
Output : foobar can somebody explain why this happened
The streams str
function returns the string by value.
That means the two s.str()
calls will return two different strings, and their respective begin
and end
iterators will be for different strings, making the std::copy
call invalid and lead to undefined behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With