std::shared_ptr类型的Vector不能释放内存
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()和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;
相关文章:
- 为什么 GCC 不能假设 std::vector::size 在这个循环中不会改变?
- 为什么初始化 std::vector 时不能使用模板整数?
- 为什么使用 std::vector 的代码不能编译,但使用 std::unique_ptr 如果没有 noexcept
- 我不能将 'fill' std::vector 构造函数与 unique_ptrs 一起使用
- 为什么 std::foreach 不能与 std::vector 一起使用<bool>?
- 不能将结构push_back() 转换为 std::vector<std::shared_ptr<theStruct>> theVector
- 使用 std::vector<Particle> 粒子;函数 .at() 不能与迭代器一起使用,它作为 for 循环中的参数
- 为什么 vector::erase 不能在带有 const 的类元素上工作
- std::仅移动类型列表:不能在 VC++ 中放入 std::vector
- 为什么我不能将 dlib 中的matrix_exp分配给 std::vector?
- 具有显式析构函数和 std::unique_ptr<> 成员的类不能在 std::vector<> 中使用?
- 函数 cv::findChessboardCorners 角不能是 std::vector<cv::P oint2f>
- 为什么我不能将 T* 包装在 std::vector 中<T>?
- 不能交换从 Vector 派生的类中的结构
- 为什么我的结构不能有 boost::variant 类型的成员,但可以有 vector<boost::variant> 类型的成员?
- 结构的 C++ 向量,为什么我不能使用 vector.at(i) 或 vector[i] 作为结构?
- 自定义分配器可用于vector,但不能用于deque(封装在队列中)
- Vector不能用{}初始化
- 具有可变范围的Std::vector不能工作
- std::shared_ptr类型的Vector不能释放内存