Reputation: 199
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
Upvotes: 7
Views: 89
Reputation: 409136
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.
Upvotes: 10