In my code I had a bug with base class not having a virtual destructor that will definitely cause a memory leak if derived class object is destroyed via base class pointer.
Being curious about it I wrote the following program:
#include <iostream>
#include <memory>
#include <vector>
class Interface {
public:
virtual void f() = 0;
};
class Printer {
public:
~Printer() {
std::cout << "Printer Dtor is called " << std::endl;
}
};
class Client : public Interface {
public:
std::vector<Printer> member;
Client() : member(4) {}
virtual void f() override final {};
};
int main() {
{
std::cout << "Unique pointer is created" << std::endl;
std::unique_ptr<Interface> ptr = std::make_unique<Client>();
std::cout << "Unique pointer goes out of the scope" << std::endl;
}
{
std::cout << "Shared pointer is created" << std::endl;
std::shared_ptr<Interface> ptr = std::make_shared<Client>();
std::cout << "Shared pointer goes out of the scope" << std::endl;
}
{
std::cout << "Shared pointer is created" << std::endl;
std::shared_ptr<Interface> ptr = std::shared_ptr<Client>(new Client);
std::cout << "Shared pointer goes out of the scope" << std::endl;
}
return 0;
}
The result is quite surprised be:
Unique pointer is created
Unique pointer goes out of the scope
Shared pointer is created
Shared pointer goes out of the scope
Printer Dtor is called
Printer Dtor is called
Printer Dtor is called
Printer Dtor is called
Shared pointer is created
Shared pointer goes out of the scope
Printer Dtor is called
Printer Dtor is called
Printer Dtor is called
Printer Dtor is called
In case of shared_ptr
the destructor of vector
is called while in case of unique_ptr
we have a memory leak.
How shared_ptr
knows which destructor to call?