gpt4 book ai didi

c++ - 使用 ostringstream 时出现意外行为

转载 作者:行者123 更新时间:2023-12-01 12:41:09 28 4
gpt4 key购买 nike

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

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()调用将返回两个不同的字符串,以及它们各自的 beginend迭代器将用于不同的字符串,使得 std::copy调用无效并导致未定义的行为。

关于c++ - 使用 ostringstream 时出现意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62407661/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com