Arjun U S
Arjun U S

Reputation: 199

Unexpected behaviour while using ostringstream

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

Answers (1)

Some programmer dude
Some programmer dude

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

Related Questions