轉自: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緩衝的效果(不信做個實驗就知道了,內存的消耗還在緩慢的增長!