为什么我需要在每次迭代使用字符串流变量的循环时清除该变量

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

本文关键字:变量 字符串 循环 清除 迭代 为什么      更新时间:2023-10-16

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

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

考虑测试用例:

#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