(转)清空std::stringstream,联系到stream的clear()和清空
2011-11-07 20:42
176 查看
原文:http://blog.csdn.net/chjp2046/article/details/5460462
使用 std::stringstream,小心 内存! 适时 清空 缓冲 ……
2007年12月14日 星期五 16:25
stringstream是个好东西,网上有不少文章,讨论如何用它实现各种数据类型的转换(比如把double或int转换为string类型)。但如果stringstream使用不当,当心内存出问题(我就吃过亏^_^)。
试试下面的代码,运行程序前打开任务管理器,过不了几十秒,所有的内存都将被耗尽!
把stream.str(""); 那一行的注释去掉,再运行程序,内存就正常了
看来stringstream似乎不打算主动释放内存(或许是为了提高效率),但如果你要在程序中用同一个流,反复读写大量的数据,将会造成大量的内存消耗,因些这时候,需要适时地清除一下缓冲 (用 stream.str("") )。
另外不要企图用 stream.str().resize(0),或 stream.str().clear() 来清除缓冲,使用它们似乎可以让stringstream的内存消耗不要增长得那么快,但仍然不能达到清除stringstream缓冲的效果(不信做个实验就知道了,内存的消耗还在缓慢的增长!)
使用 std::stringstream,小心 内存! 适时 清空 缓冲 ……
2007年12月14日 星期五 16:25
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缓冲的效果(不信做个实验就知道了,内存的消耗还在缓慢的增长!)
相关文章推荐
- 清空std::stringstream,联系到stream的clear()和清空
- 清空std::stringstream,联系到stream的clear()和清空
- [C++]使用std::stringstream小心内存,适时清空缓冲。
- C++stringstream的clear()清空误区
- 使用 std::stringstream,小心 内存! 适时 清空 缓冲 ……
- 使用 std::stringstream,小心 内存! 适时 清空 缓冲 ……
- C++stringstream的clear()清空误区
- 使用 std::stringstream,小心 内存! 适时 清空 缓冲 ……
- c++ stringstream 的clear()清空误区
- how to clear stringstream
- 实战c++中的string系列--std:vector<char> 和std:string相互转换(vector to stringstream)
- std::ifstream 打开文件,获得文件流 并赋给std::string
- std::ifstream 打开文件,获得文件流 并赋给std::string
- 实战c++中的string系列--std:vector<char> 和std:string相互转换(vector to stringstream)
- 通过std::stringstream的read和write实现对二进制流的读写
- c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined
- stringstream clear()的误区
- std::stringstream只适合作字符串格式化
- std::getline (string) & std::stringstream::str
- Convert asio::streambuf to std::string