fork download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. struct base {};
  5.  
  6. struct derived : base { ~derived() { std::cout << "derived::~derived\n" ; } };
  7.  
  8. int main()
  9. {
  10. {
  11. std::shared_ptr<base> p1( new derived ) ;
  12. std::shared_ptr<derived> p2( new derived ) ;
  13. std::shared_ptr<base> p3 = p2 ;
  14. std::shared_ptr<base> p4 = std::make_shared<derived>() ;
  15. }
  16. std::cout << "the three derived class objects should have been destroyed by now\n" ;
  17.  
  18. {
  19. std::cout << "without a virtual destructor for base, there is trouble here\n" ;
  20. std::shared_ptr<base> p( static_cast<base*>( new derived ) ) ;
  21. }
  22. std::cout << "the wrong destructor would have been called for the derived class object\n" ;
  23. }
  24.  
Success #stdin #stdout 0s 2988KB
stdin
Standard input is empty
stdout
derived::~derived
derived::~derived
derived::~derived
the three derived class objects should have been destroyed by now
without a virtual destructor for base, there is trouble here
the wrong destructor would have been called for the derived class object