[英]Clearing memory allocated by vector
我使用了后面的代碼和gnome系統監視器來查看內存如何分配到內存中:
#include <iostream>
#include <string>
#include <vector>
using std::string;
int main(void)
{
string sentence;
std::vector<string>words{};
string seperators{" ,:;!."};
std::cout<<"Please enter the line terminated by an asterisk"<<std::endl;
std::getline(std::cin, sentence, '*');
std::cout<<"The sentence is: "<<sentence<<std::endl;
size_t start{0};
size_t end{};
int count{};
while(start != string::npos)
{
end = sentence.find_first_of(seperators, start + 1);
string word = sentence.substr(start, end - start);
std::cout<<word<<std::endl;
words.push_back(word);
start = sentence.find_first_not_of(seperators, end +1);
if(count++ == 10000000)
{
std::cout<<"^^^^^^^^^^^^^^^^^^^^^^^^^^^"<<"here"<<std::endl;
break;
}
}
words.clear();
//for(auto word: words)
//{
// std::cout<<word <<std::endl;
// }
std::cin>>start;
}
隨着while循環的繼續,內存消耗儀表開始以穩定的速率連續增加,並且在循環中斷達到10000000的計數后,程序執行words.clear()函數,該函數應該已清除,但是,它沒有。 記憶說,消耗達到53%,直到程序結束。
如果.clear()不是釋放向量所釋放內存的方法,那么,我們如何釋放它呢? 它本應該自動完成,但我的實驗表明它不是。 或者,代碼有問題嗎?
你可以調用clear,這將破壞所有對象,但這不會釋放內存。 循環通過各個元素也無濟於事(你甚至建議對這些對象采取什么行動?)你能做的是:
vector<tempObject>().swap(tempVector);
這將創建一個沒有分配內存的空向量,並將其與tempVector交換,從而有效地釋放內存。
C ++ 11還有函數shrink_to_fit,你可以在調用clear()之后調用它,理論上它會縮小容量以適應大小(現在為0)。 但是,這是一個非綁定請求,您的實現可以自由忽略它。
在clear()
之后調用shrink_to_fit()
(C ++ 11添加clear()
以釋放std::vector
保留的未使用的內存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.