fork(1) download
  1. #include <iostream>
  2.  
  3. struct X
  4. {
  5. X() { std::cout << "X ctor\n"; }
  6. ~X() { std::cout << "X dtor\n"; }
  7. };
  8.  
  9. struct M
  10. {
  11. M()
  12. {
  13. if( ++cnt == 1) x = new X;
  14. }
  15. ~M()
  16. {
  17. if( !--cnt ) delete x;
  18. }
  19. private:
  20. static int cnt;
  21. static X* x;
  22. };
  23.  
  24. int M::cnt = 0;
  25. X* M::x = nullptr;
  26.  
  27. int main() {
  28.  
  29. {
  30. M m;
  31. M m2;
  32. }
  33.  
  34. M* mp = new M;
  35.  
  36. M m3;
  37.  
  38. delete mp;
  39.  
  40. return 0;
  41. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
X ctor
X dtor
X ctor
X dtor