为什么我需要在使用它的循环的每次迭代中清除 stringstream 变量

Why do I need to clear a stringstream variable with each iteration of a loop in which it is used

在我的学校,我们必须遵循一种风格指南,该指南规定我们必须在使用它的函数顶部声明每个变量,而不是在使用它之前。这通常意味着您必须在循环内使用变量时重置或清除变量,因为它们未在该循环内声明。我不明白为什么每次循环迭代都需要 "clear"ed 一个 stringstream 变量,我希望有人能阐明这一点。我知道如何清除它只是想知道为什么有必要。

这背后的基本原理是在循环内创建 对象会导致性能下降。 ::std::stringstream 是这些对象之一,一直创建和销毁字符串流是一个常见的错误。然而,这样的规则不适用于 light 对象,例如原始类型。

考虑 test case

#include <chrono>
#include <sstream>
#include <iostream>
#include <cstdlib>  

int main()
{
    using namespace std;
    using namespace chrono;

    auto const loops_count{1000000};
    auto const p1{high_resolution_clock::now()};
    {
        stringstream ss{};
        for(auto i{loops_count}; 0 != i; --i)
        {
            ss.str(string{}); // clear
            ss << 1;
        }
    }
    auto const p2{high_resolution_clock::now()};
    {
        for(auto i{loops_count}; 0 != i; --i)
        {
            stringstream ss{}; // recreate
            ss << 1;
        }
    }
    auto const p3{high_resolution_clock::now()};
    cout << duration_cast< milliseconds >(p2 - p1).count() << "ms "
        << duration_cast< milliseconds >(p3 - p2).count() << "ms" 
        << endl;
    return EXIT_SUCCESS;
}

第一个循环 35ms,第二个 431ms