gpt4 book ai didi

c++ - std::shared_ptr 的 vector 未释放内存

转载 作者:行者123 更新时间:2023-12-01 14:56:17 25 4
gpt4 key购买 nike

第一次在这里发帖,我不是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 类为 A 创建一个 std::shared_ptrs vector 并将其返回。然后我在一个名为 myfunc 的函数中将这些局部 vector 组装成一个大的全局 vector 。为了测试当我想缩小 globA 的大小时内存是否被释放,我调用 globA.clear() 和 globA.shrink_to_fit()。

问题是调用 clear() 和 shrink_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;

关于c++ - std::shared_ptr 的 vector 未释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23521318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com