将指针存储到向量时发生内存泄漏

Memory leak when storing pointers into vector

我已经阅读了多个关于同一主题的类似问题,但我无法通过关注它们来解决我的问题。

我想在向量中存储指针,但发现内存泄漏。我的代码如下。

#include <iostream>
#include <vector>
#include <memory>

class Base 
{
    public:
       virtual ~Base() {}
};

class Derived : public Base {};

std::vector<std::unique_ptr<Base>> bv;

int main()
{
    for (int i = 0; i < 10; i++)
       bv.emplace_back(std::make_unique<Base>(Derived()));

    bv.clear();

    return 0;
}

Valgrind 报告:"still reachable: 72,704 bytes in 1 blocks"。如果我不使用 unique_ptr,而只使用 bv.emplace_back(new Derived);delete 明确来自向量的指针,我会遇到同样的问题。是什么导致泄漏?

看起来您实际上存储了 Base class 的实例。 Derived() 在堆栈上创建一个对象,然后 make_unique 将其传递给 Base 的构造函数。这是对象切片。 这不能解释泄漏,但表明代码可能无法达到您的预期。

补充: 已删除:free() 并不总是 return 内存返回给系统。 Libc 将为将来的 malloc() 保留此内存。这可能解释了您的观察结果。

我同意@cmaster 下面的评论。 Valgrind 确实跟踪 malloc/free。经过一番研究后,我在 Whosebug 上发现了另一个问题,它解释了观察结果。

包含 iostream

"Many implementations of the C++ standard libraries use their own memory pool allocators."他们就是不释放内存。

更多详情: