Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected behaviour while using ostringstream

Tags:

c++

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

like image 345
Arjun U S Avatar asked Jun 16 '20 11:06

Arjun U S


1 Answers

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.

like image 80
Some programmer dude Avatar answered Nov 10 '22 18:11

Some programmer dude