首页 > 解决方案 > 使用 ostringstream 时出现意外行为

问题描述

在以下情况下获得不同的输出

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];

输出: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];

输出: foobar 有人可以解释为什么会这样

标签: c++

解决方案


流函数按值str返回字符串。

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


推荐阅读