![](/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.