[英]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()
调用将返回两个不同的字符串,并且它们各自的begin
和end
迭代器将用于不同的字符串,从而使std::copy
调用无效并导致未定义的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.