stringstream clear()的误区

来源:互联网 发布:网络交友新时空图片 编辑:程序博客网 时间:2024/05/16 02:04

转自:http://blog.163.com/mageng11@126/blog/static/1408083742012214104532291/ 

stringstream是个好东西,网上有不少文章,讨论如何用它实现各种数据类型的转换(比如把double或int转换为string类型)。但如果stringstream使用不当,当心内存出问题(我就吃过亏^_^)。

试试下面的代码,运行程序前打开任务管理器,过不了几十秒,所有的内存都将被耗尽!


#include <cstdlib>  #include <iostream>  #include <sstream>  using namespace std;  ///////////////////////////////////////////////int main(int argc, char * argv[])  {  std::stringstream stream;  string str;  while(1)  {      //clear(),这个名字让很多人想当然地认为它会清除流的内容。   //实际上,它并不清空任何内容,它只是重置了流的状态标志而已!  stream.clear();     // 去掉下面这行注释,清空stringstream的缓冲,每次循环内存消耗将不再增加!  //stream.str("");        stream<<"sdfsdfdsfsadfsdafsdfsdgsdgsdgsadgdsgsdagasdgsdagsadgsdgsgdsagsadgs ";   stream>>str;      // 去掉下面两行注释,看看每次循环,你的内存消耗增加了多少!  //cout<<"Size of stream = "<<stream.str().length()<<endl;  //system("PAUSE");  }  system("PAUSE ");  return EXIT_SUCCESS;  } 

复制代码

把stream.str(""); 那一行的注释去掉,再运行程序,内存就正常了

看来stringstream似乎不打算主动释放内存(或许是为了提高效率),但如果你要在程序中用同一个流,反复读写大量的数据,将会造成大量的内存消耗,因些这时候,需要适时地清除一下缓冲 (用 stream.str("") )。

另外不要企图用 stream.str().resize(0),或 stream.str().clear() 来清除缓冲,使用它们似乎可以让stringstream的内存消耗不要增长得那么快,但仍然不能达到清除stringstream缓冲的效果(不信做个实验就知道了,内存的消耗还在缓慢的增长!


0 0
原创粉丝点击