C++: If an exception is thrown, are objects that go out of scope destroyed?

前端 未结 3 919
失恋的感觉
失恋的感觉 2021-01-18 06:00

Normally it would be destructed upon the scope ending.. I could see issues occurring if exceptions were thrown though.

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-18 06:47

    Yes any scope bound variables will be destroyed.

    void work()
    {
         Foo a;
         Foo* b = new Foo;
         // ... later
    
         // exception thrown
    
         delete b;
    }
    

    In this example a's destructor would be called when the exception was thrown as the stack unwound, but the memory pointed to by b would be leaked since it would never reach the delete call. This is one of the many reasons why RAII is so helpful.

提交回复
热议问题