fork download
  1. #include <iostream>
  2. #include <memory>
  3. #include <vector>
  4.  
  5. class Node {
  6. public:
  7. using NodePtr = std::unique_ptr<Node>;
  8. Node( char lc, NodePtr l, NodePtr r ) :
  9. c( lc ), left( std::move(l) ), right( std::move(r) )
  10. {
  11. }
  12. ~Node();
  13.  
  14. private:
  15. NodePtr left;
  16. NodePtr right;
  17. char c;
  18. };
  19.  
  20.  
  21. Node::~Node()
  22. {
  23. std::cout << "destroying " << c << std::endl;
  24.  
  25. if( ! (left || right) ) // optimization
  26. return;
  27. std::vector<NodePtr> nodes;
  28. auto populate = [&nodes] ( Node *n ) {
  29. if( n->left ) nodes.push_back( std::move( n->left ) );
  30. if( n->right ) nodes.push_back( std::move( n->right ) );
  31. };
  32. populate( this );
  33. while( !nodes.empty() ) {
  34. auto n = std::move( nodes.back() );
  35. nodes.pop_back();
  36. populate( n.get() );
  37. }
  38. }
  39.  
  40.  
  41. int main() {
  42. Node root( 'A',
  43. std::make_unique<Node>( 'l', std::make_unique<Node>( 'L', nullptr, nullptr ), nullptr ),
  44. std::make_unique<Node>( 'r', std::make_unique<Node>( 'R', nullptr, nullptr ), nullptr ) );
  45. return 0;
  46. }
Success #stdin #stdout 0.01s 5468KB
stdin
Standard input is empty
stdout
destroying A
destroying r
destroying R
destroying l
destroying L