fork download
  1. #include <iostream>
  2. #include <memory>
  3. #include <vector>
  4.  
  5. typedef std::vector<class A*> AVector;
  6.  
  7. class A
  8. {
  9. protected: // so B can access it.
  10. int m_i;
  11. public:
  12. A(int i_) : m_i(i_)
  13. {
  14. std::cout << "CTor'd A(i) " << (void*)this
  15. << " with " << m_i << std::endl;
  16. }
  17. A(int i_, bool) : m_i(i_)
  18. {
  19. std::cout << "CTor'd A(i, b) " << (void*)this
  20. << " with " << m_i << std::endl;
  21.  
  22. }
  23.  
  24. virtual ~A()
  25. {
  26. std::cout << "DTor'd A " << (void*)this << " with " << m_i << std::endl;
  27. }
  28. };
  29.  
  30. class B : public A
  31. {
  32. int m_j;
  33. public:
  34. B(int i_, int j_) : A(i_, true), m_j(j_)
  35. {
  36. std::cout << "CTor'd B(i, j) " << (void*)this
  37. << " with " << m_i << ", " << m_j << std::endl;
  38. }
  39.  
  40. virtual ~B()
  41. {
  42. std::cout << "DTor'd B " << (void*)this
  43. << " with " << m_i << ", " << m_j << std::endl;
  44. }
  45. };
  46.  
  47. int main()
  48. {
  49. AVector avec;
  50.  
  51. std::cout << "create A(1)" << std::endl;
  52. avec.push_back(new A(1)); // allocated an "A" on the heap.
  53. std::cout << "create B(2, 1)" << std::endl;
  54. avec.push_back(new B(2, 1)); // allocated a "B" on the heap.
  55. std::cout << "create B(2, 2)" << std::endl;
  56. avec.push_back(new B(2, 2));
  57. std::cout << "create A(3) " << std::endl;
  58. avec.push_back(new A(3));
  59. std::cout << "populated avec" << std::endl;
  60.  
  61. A* ptr = avec[2]; // take the pointer of what is actually a B
  62. avec.erase(avec.begin() + 2); // remove it from the vector.
  63. std::cout << "removed entry 2 from the vector" << std::endl;
  64. // 'ptr' is still valid because it's an allocation, and C++ doesn't
  65. // garbage collect heap allocations. We have to 'delete' it ourselves.
  66. // Also note that because A and B have virtual destructors,
  67. // you will see both of them called.
  68. delete ptr;
  69.  
  70. // Now watch what DOESN'T happen as we exit.
  71. // everything we CTOR'd that doesn't get DTORd is a leak.
  72. return 0;
  73. }
  74.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
create A(1)
CTor'd A(i) 0x9d94008 with 1
create B(2, 1)
CTor'd A(i, b) 0x9d94028 with 2
CTor'd B(i, j) 0x9d94028 with 2, 1
create B(2, 2)
CTor'd A(i, b) 0x9d94018 with 2
CTor'd B(i, j) 0x9d94018 with 2, 2
create A(3) 
CTor'd A(i) 0x9d94038 with 3
populated avec
removed entry 2 from the vector
DTor'd B 0x9d94018 with 2, 2
DTor'd A 0x9d94018 with 2