![](/img/trans.png)
[英]Is this std::vector and std::shared_ptr memory leakage a bug?
[英]Vector of std::shared_ptr not freeing memory
第一次在這里發帖,而且我不是CS專家,請耐心等待。 我的代碼大小合適,因此我將在下面發布問題的基本版本,然后進行解釋。
#include <vector>
#include <memory>
class A{
public:
A(){};
double dbl[20];
};
typedef std::shared_ptr<A> A_ptr;
class B{
public:
const std::vector<A_ptr> createAVector(){
std::vector<A_ptr> vec;
for(int i=0; i<4; i++){
vec.push_back(A_ptr( new A() ));
}
return vec;
}
};
int myfunc(){
// Do Stuff...
std::vector<A_ptr> globvec;
B b;
for(int i=0; i<1e6; i++){
const std::vector<A_ptr> locvec = b.createAVector();
for(int i=0; i<locvec.size(); i++) globvec.push_back(locvec[i]);
}
globvec.clear();
globvec.shrink_to_fit();
// Do more stuff...
return 1;
}
int main(){
myfunc();
for(auto i=0; i<3; i++){
myfunc();
}
return 1;
}
編輯:我修改了代碼,因此它實際上可以編譯。
所以,基本上我有兩節課。 A類存儲實際數據。 除其他事項外,類B創建一個向量std :: shared_ptrs到A並將其返回。 然后,在名為myfunc的函數中,將這些局部向量組合成一個大的全局向量。 為了測試當我想縮小globA的大小時是否釋放了內存,我調用globA.clear()和globA.shrink_to_fit()。
問題是調用clear()和rinkle_to_fit()不會釋放所有創建的A的內存。
我在這里做錯什么嗎? 知道會發生什么嗎?
任何幫助將不勝感激。
謝謝!
約翰
您的代碼很好。 你可以基本上“證明”你是不漏A
對象這... ...(我也不得不減少從1E6的迭代次數得到任何合理的運行時間)。
有更復雜的工具可以查找內存泄漏。 我知道對於Linux我們使用Valgrind。 我不知道什么是Windows。
class A{
public:
A() { std::cout << "Created A " << ++num_instances << std::endl;}
~A() { std::cout << "Destroyed A " << --num_instances << std::endl;}
static int num_instances; // So not thread-safe
double dbl[20];
};
int A::num_instances = 0;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.