Wystarczy dodać jeszcze jeden przykład na Daniel Lidström's answer
As long as you always store your allocated objects in a shared_ptr, then you really don't need a virtual destructor.
Jeśli ktoś używa shared_ptr tak:
std::shared_ptr<Base> b(new Concrete);
Następnie destruktor betonu i destruktor bazowy są wywoływane przy zniszczeniu obiektu.
Jeśli ktoś używa shared_ptr tak:
Base* pBase = new Concrete;
std::shared_ptr<Base> b(pBase);
Potem tylko destruktor bazowa jest wywoływana na zniszczenie obiektu.
to an example
#include <iostream> // cout, endl
#include <memory> // shared_ptr
#include <string> // string
struct Base
{
virtual std::string GetName() const = 0;
~Base() { std::cout << "~Base\n"; }
};
struct Concrete : public Base
{
std::string GetName() const
{
return "Concrete";
}
~Concrete() { std::cout << "~Concrete\n"; }
};
int main()
{
{
std::cout << "test 1\n";
std::shared_ptr<Base> b(new Concrete);
std::cout << b->GetName() << std::endl;
}
{
std::cout << "test 2\n";
Base* pBase = new Concrete;
std::shared_ptr<Base> b(pBase);
std::cout << b->GetName() << std::endl;
}
}
możliwe duplikat [wirtualnych destruktory domyślne C++] (http://stackoverflow.com/questions/827196/virtual-default-destructors-in-c) –