使用ostringstream时出现意外行为

7

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

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

1个回答

10

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

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


所以,当调用 str() 函数每次在内存中创建一个字符串对象,然后返回迭代器。 - Arjun U S
1
@ArjunUS 是的,没错。而且迭代器必须来自同一个字符串对象才能“兼容”。 - Some programmer dude

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接