fork download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. template <typename T>
  5. struct Node {
  6. T m_info;
  7.  
  8. std::shared_ptr<Node<T>> m_next;
  9. std::shared_ptr<Node<T>> m_prev;
  10. };
  11.  
  12. template <typename T>
  13. struct List {
  14.  
  15. void print() {
  16. auto n = m_head.get();
  17.  
  18. while (n) {
  19. std::cout << n->m_info << '\n';
  20.  
  21. n = n->m_next.get();
  22. }
  23. }
  24.  
  25. void add(T value) {
  26. auto node = std::make_shared<Node<T>>(Node<T>{ value, m_head, nullptr});
  27. if (m_head) m_head.get()->m_prev = m_head;
  28. m_head = node;
  29. }
  30.  
  31. private:
  32. std::shared_ptr<Node<T>> m_head;
  33. };
  34.  
  35. struct noisy_at_dying {
  36. int id;
  37.  
  38. ~noisy_at_dying() { std::cout << id << " is dying\n"; }
  39. };
  40.  
  41. // for print
  42. std::ostream& operator<<(std::ostream& os, const noisy_at_dying& nad) {return os << nad.id;}
  43.  
  44. int main() {
  45.  
  46. {
  47. List<noisy_at_dying> l;
  48.  
  49. for (auto i = int{ 0 }; i < 3; ++i)
  50. l.add({ i });
  51.  
  52. std::cout << "\nThe list is populated. Printing...\n\n";
  53.  
  54. l.print();
  55.  
  56. std::cout << "\nThe list is about to be destroyed...\n\n";
  57. }
  58.  
  59. std::cout << "\nThe list has been destroyed.\n";
  60. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
0 is dying
0 is dying
1 is dying
1 is dying
2 is dying
2 is dying

The list is populated. Printing...

2
1
0

The list is about to be destroyed...

2 is dying

The list has been destroyed.