c++ - How do you implement the destructor in CRTP? -
are destructors required virtual when implementing curiously recurring template pattern (crtp)? , if not, proper non-virtual implementation?
i'll provide example make things easier:
template<typename t> class base { public: virtual ~base() { // should virtual? non-virtual? std::cout << "base::~base()\n"; } }; class derived : public base<derived> { public: ~derived() override { std::cout << "derived::~derived()\n"; } }; int main() { base<derived>* b = new derived; delete b; } result:
derived::~derived() base::~base() edit: updated example use runtime polymorphism virtual destructor required proper cleanup.
a crtp base class no different other base class in sense. need virtual destructor if going delete object of type derived via pointer base<derived>. otherwise, virtual destructor not required.
base<derived>* b = new derived; delete b; // base<derived>::~base<derived> must virtual
Comments
Post a Comment