fork download
  1. #include <iostream>
  2. #include <new>
  3.  
  4. using namespace std;
  5.  
  6. template <typename T>
  7. class SmartWrapper
  8. {
  9. private:
  10. T * obj;
  11. public:
  12. SmartWrapper(T * newObj)
  13. {
  14. cout << "Wrapper: Begin" << endl;
  15. obj = newObj;
  16. }
  17. ~SmartWrapper()
  18. {
  19. delete obj;
  20. cout << "Wrapper: End" << endl;
  21. }
  22. };
  23.  
  24. class Person
  25. {
  26. public:
  27. Person()
  28. {
  29. cout << "Person: Begin" << endl;
  30. }
  31. ~Person()
  32. {
  33. cout << "Person: End" << endl;
  34. }
  35. };
  36.  
  37. class Dog
  38. {
  39. public:
  40. Dog()
  41. {
  42. cout << "Dog: Begin" << endl;
  43. }
  44. ~Dog()
  45. {
  46. cout << "Dog: End" << endl;
  47. }
  48. };
  49.  
  50. int main()
  51. {
  52. // we should have the same number of begins and ends.
  53. // we actually have half of ends because objects created
  54. // without smart pointers are not deleted after each iteration.
  55. for(int i = 0; i < 2; i++)
  56. {
  57. Dog* c1 = new Dog();
  58. Person* c2 = new Person();
  59. SmartWrapper<Dog> s1(new Dog());
  60. SmartWrapper<Person> s2(new Person());
  61. }
  62.  
  63. return 0;
  64. }
  65.  
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
Dog: Begin
Person: Begin
Dog: Begin
Wrapper: Begin
Person: Begin
Wrapper: Begin
Person: End
Wrapper: End
Dog: End
Wrapper: End
Dog: Begin
Person: Begin
Dog: Begin
Wrapper: Begin
Person: Begin
Wrapper: Begin
Person: End
Wrapper: End
Dog: End
Wrapper: End