Advertisement
Semper_Idem

C++ Object Destruction

Oct 14th, 2022
1,259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1. senchev@senchev-yoga:~/scratch$ cat test.cpp
  2. #include <iostream>
  3.  
  4. class Foo {
  5. public:
  6.   Foo() { std::cout << "Constructing Foo: " << this << std::endl; }
  7.   ~Foo() { std::cout << "Destructing Foo: " << this << std::endl; }
  8.   int value;
  9. };
  10.  
  11. class Bar {
  12. public:
  13.   Bar() { std::cout << "Constructing Bar: " << this << std::endl; }
  14.   ~Bar() { std::cout << "Destructing Bar: " << this << std::endl; }
  15.   Foo foo;
  16. };
  17.  
  18. class Baz {
  19. public:
  20.   Baz() {
  21.     std::cout << "Constructing Baz: " << this << std::endl;
  22.         bar = new Bar();
  23.   }
  24.   ~Baz() {
  25.         std::cout << "Destructing Baz: " << this << std::endl;
  26.         delete bar;
  27.   }
  28.   Bar *bar;
  29.   Foo foo;
  30. };
  31.  
  32. int main(void) {
  33.   std::cout << "1" << std::endl;
  34.   Foo foo{};
  35.   std::cout << "2" << std::endl;
  36.   Bar *bar = new Bar();
  37.   std::cout << "3" << std::endl;
  38.   Baz baz{};
  39.   std::cout << "4" << std::endl;
  40.   delete bar;
  41.   std::cout << "5" << std::endl;
  42.   return 0;
  43. }
  44. senchev@senchev-yoga:~/scratch$ g++ test.cpp -o test
  45. senchev@senchev-yoga:~/scratch$ ./test
  46. 1
  47. Constructing Foo: 0x7fff484236b4
  48. 2
  49. Constructing Foo: 0x5639eed3c2c0
  50. Constructing Bar: 0x5639eed3c2c0
  51. 3
  52. Constructing Foo: 0x7fff484236c8
  53. Constructing Baz: 0x7fff484236c0
  54. Constructing Foo: 0x5639eed3c2e0
  55. Constructing Bar: 0x5639eed3c2e0
  56. 4
  57. Destructing Bar: 0x5639eed3c2c0
  58. Destructing Foo: 0x5639eed3c2c0
  59. 5
  60. Destructing Baz: 0x7fff484236c0
  61. Destructing Bar: 0x5639eed3c2e0
  62. Destructing Foo: 0x5639eed3c2e0
  63. Destructing Foo: 0x7fff484236c8
  64. Destructing Foo: 0x7fff484236b4
  65. senchev@senchev-yoga:~/scratch$
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement