在以下情况下得到不同的输出
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 谁能解释一下为什么会发生这种情况?
流 str
函数返回字符串 按价值.
这意味着这两个 s.str()
呼叫将返回 两根弦以及它们各自 begin
和 end
迭代器将针对不同的字符串,使 std::copy
呼叫无效,导致 未定义行为.