I have read multiple similar questions on the same topic that have been asked, but I was not able to resolve my issue by following them.
I want to store pointers in a vector, but I see a memory leak. My code is as follows.
#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 reports: "still reachable: 72,704 bytes in 1 blocks". I have the same issue if I don't use unique_ptr
, and just use bv.emplace_back(new Derived);
, and delete
the pointers explicitly from the vector. What is causing the leak?