使用std::shared_ptr到std::vector时内存泄漏
Memory leak when using std::shared_ptr to std::vector
我有一个图像类:
class Image{
public:
Image()
{
vector_ptr = std::make_shared<std::vector<Feature>>(feature_vector);
}
std::shared_ptr<std::vector<Feature>> calculate_vector()
{
// iterates over a space of possible features, calling
// vector_ptr->push_back(Feature(type, i, j, w, h, value))
return vector_ptr;
}
std::shared_ptr<std::vector<Feature>> get_vector()
{
return vector_ptr;
}
void clear_vector()
{
vector_ptr->clear();
}
private:
std::vector<Feature> feature_vector;
std::shared_ptr<std::vector<Feature>> vector_ptr;
};
其中特征由:
给出struct Feature
{
Feature(int type, int i, int j, int w, int h, double value);
void print();
int type;
int i, j;
int w, h;
double value;
};
但是在连续调用calculate_vector()和clear_vector()之后,htop表示存在内存泄漏
如何解决这个问题?(特征向量非常大)
vector_ptr
是feature_vector
的副本,它不是围绕它的共享包装器。所以如果你想释放feature_vector.clear();
的内存,你也需要调用它。
相关文章:
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- 为什么这个 std::queue/指向结构的指针列表直到 List.Size() == 0 才释放内存?
- 使 std::vector 分配对齐内存的现代方法
- std::unordered_map析构函数不释放内存?
- std::p romise::set_value() 和 std::future::wait() 是否提供内存围栏?
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- 在共享缓冲区内存中创建 ::std::string 对象
- 内存未释放 std::list<std::shared_ptr<std::string>> C++
- <char> 使用 Vulkan 映射内存时如何使用 std::vector 而不是 void**?
- 我可以将新的 std::tuple 放入内存映射区域,并在以后读回吗?
- 如何防止使用 std::shared_ptr 的代码中的内存泄漏
- C++ 中 std::vector 的内存问题
- std::set 是否将对象连续存储在内存中?
- 如何在窗口之间移动 std::unique_ptr 而不会冒内存泄漏的风险?
- 为什么"std::uninitialized_copy"通常取消对未初始化内存的迭代器的引用不是未定
- vector是否为std::移动的对象连续分配内存
- Valgrind 在 std::make_unique 中显示内存泄漏
- std::initializer_list 堆是否分配内存?
- std::unordered_set 中的元素如何存储在C++内存中?