使用 ostringstream 时的意外行为

问题描述 投票:0回答:1

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

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++
1个回答
10
投票

str 函数返回字符串 按价值.

这意味着这两个 s.str() 呼叫将返回 两根弦以及它们各自 beginend 迭代器将针对不同的字符串,使 std::copy 呼叫无效,导致 未定义行为.

© www.soinside.com 2019 - 2024. All rights reserved.