• Source
    1. // CTORException.cpp : Defines the entry point for the console application.
    2. //
    3.  
    4. #include <memory>
    5. #include <stdexcept>
    6. #include <iostream>
    7. using namespace std;
    8.  
    9. class object_t
    10. {
    11. public:
    12. object_t()
    13. {
    14. cout << "object_t CTOR" << endl;
    15. }
    16. ~object_t(){
    17. cout << "object_t DTOR" << endl;
    18. }
    19. };
    20.  
    21. class test_t
    22. {
    23. public:
    24. test_t() try
    25. : ptr(nullptr) //NOTE that I start with member which cannot throw
    26. , mem(new object_t)
    27. {
    28. cout << "test_t CTOR" << endl;
    29. ptr = new object_t;
    30. throw logic_error("exception just to test...");
    31. }
    32. catch (...)
    33. {
    34. cout << "here we handle our dynamic allocation" << endl;
    35. if (ptr != nullptr)
    36. delete ptr;
    37. throw;
    38. }
    39. ~test_t()
    40. {
    41. cout << "test_t DTOR" << endl;
    42. delete ptr;
    43. }
    44. private:
    45. object_t* ptr;
    46. unique_ptr<object_t> mem;
    47. };
    48.  
    49. int main()
    50. {
    51. try
    52. {
    53. test_t t;
    54. }
    55. catch (exception& roEx)
    56. {
    57. cout << roEx.what() << endl;
    58. }
    59. return 0;
    60. }
    61.  
    62.