简体   繁体   English

使用 ostringstream 时出现意外行为

[英]Unexpected behaviour while using ostringstream

Getting different output in following cases在以下情况下获取不同的 output

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 Output: 富

 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 Output:foobar 有人可以解释为什么会发生这种情况

The streams str function returns the string by value .str function按值返回字符串。

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 .这意味着两个s.str()调用将返回两个不同的字符串,并且它们各自的beginend迭代器将用于不同的字符串,从而使std::copy调用无效并导致未定义的行为

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM