C ++: calling the timing of destructor

Conclusion: Only when the constructor of the class of an instance of an object is finished , and when the object is out of scope , the destructor will be performed.

If an exception is thrown during the execution of the constructor, destructor will not be called

The test code:

 1 class Test
 2 {
 3 public:
 4     Test()
 5     {
 6         cout << "Test() begin..." << endl;
 7         throw(0);
 8         cout << "Test() end" << endl;
 9     }
10     ~Test()
11     {
12         cout << "~Test()" << endl;
13     }
14 };
15 
16 int main()
17 {
18     try
19     {
20         Test t1;
21     }
22     catch (...)
23     {
24         cout << "........................................." << endl;
25     }
26     return 0;
27 }

Results of the:

 

 

The introduction of such an unsafe situation

. 1  class Example
 2  {
 . 3  public :
 . 4      Example ()
 . 5      {
 . 6          m_p1 = new new  int [ 100 ];
 . 7          m_p2 = new new  int [ 100 ];         // if this code throws an exception m_p2 resources have been allocated will automatically release
 8                                      // However, since Example constructor has not been fully executed, so that when the time out of scope
 . 9                                      // Example destructor will not be performed, resulting in resource allocation m_p1 never released
 10                                      @ PS: if the object the constructor has not been fully executed when the object is out of scope but still perform what destructor will happen?
11                                      // PS: In this case, m_p2 clearly has no resources managed by it, but still it was finally delete [], continue to pose an unreasonable result
12     }
13     ~Example()
14     {
15         delete[] m_p1;
16         delete[] m_p2;
17     }
18 private:
19     int* m_p1;
20     int* m_p2;
21 };

 

Further launched Conclusion: Do not managing multiple resources in a single class, if you have to manage multiple resources, create multiple resource management classes, one to one drop of the allocation of these resources to the management class to manage the resources, then the resource management class as a member in the target class.

Guess you like

Origin www.cnblogs.com/XiaoXiaoShuai-/p/11627084.html