fork download
  1. #include <string>
  2. #include <stdexcept>
  3. #include <iostream>
  4. using namespace std;
  5.  
  6. class throwsecond
  7. {
  8. static int count;
  9. public:
  10. throwsecond(const string &)
  11. {
  12. if (count ++)
  13. {
  14. count = 0;
  15. throw runtime_error("Kaboom!");
  16. }
  17. cout << "Constructed\n";
  18. }
  19. ~throwsecond()
  20. {
  21. cout << "Destructed\n";
  22. }
  23. };
  24.  
  25. int throwsecond::count = 0;
  26.  
  27. class bad_example
  28. {
  29. throwsecond * a;
  30. throwsecond * b;
  31. public:
  32. bad_example(): a(nullptr), b(nullptr)
  33. {
  34. }
  35. bad_example (const string& a,
  36. const string& b)
  37. {
  38. this->a = new throwsecond(a);
  39. this->b = new throwsecond(b);
  40. }
  41. ~bad_example()
  42. {
  43. delete a;
  44. delete b;
  45. }
  46. };
  47.  
  48. class good_example
  49. {
  50. throwsecond * a;
  51. throwsecond * b;
  52. public:
  53. good_example(): a(nullptr), b(nullptr)
  54. {
  55. }
  56. good_example (const string& a,
  57. const string& b) : good_example{}
  58. {
  59. this->a = new throwsecond(a);
  60. this->b = new throwsecond(b);
  61. }
  62. ~good_example()
  63. {
  64. delete a;
  65. delete b;
  66. }
  67. };
  68.  
  69. int main()
  70. {
  71. cout << "Bad example\n";
  72. try
  73. {
  74. bad_example("", "");
  75. }
  76. catch (...)
  77. {
  78. cout << "Caught exception\n";
  79. }
  80. cout << "Good example\n";
  81. try
  82. {
  83. good_example("", "");
  84. }
  85. catch (...)
  86. {
  87. cout << "Caught exception\n";
  88. }
  89. }
  90.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Bad example
Constructed
Caught exception
Good example
Constructed
Destructed
Caught exception