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

空扰寡人 提交于 2019-12-30 21:21:53

问题


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


回答1:


Yes.

C++ Standard n3337

15 Exception handling

§ 15.2 Constructors and destructors

1) As control passes from a throw-expression to a handler, destructors are invoked for all automatic objects constructed since the try block was entered. The automatic objects are destroyed in the reverse order of the completion of their construction.

2) An object of any storage duration whose initialization or destruction is terminated by an exception will have destructors executed for all of its fully constructed subobjects (excluding the variant members of a union-like class), that is, for subobjects for which the principal constructor (12.6.2) has completed execution and the destructor has not yet begun execution. Similarly, if the non-delegating constructor for an object has completed execution and a delegating constructor for that object exits with an exception, the object’s destructor will be invoked. If the object was allocated in a new-expression, the matching deallocation function (3.7.4.2, 5.3.4, 12.5), if any, is called to free the storage occupied by the object.

3) The process of calling destructors for automatic objects constructed on the path from a try block to a throw-expression is called “stack unwinding.” If a destructor called during stack unwinding exits with an exception, std::terminate is called (15.5.1). [ Note: So destructors should generally catch exceptions and not let them propagate out of the destructor. — end note ]

example:

SomeClass c;              // declared before try{} so it is
                          // still valid in catch{} block
try {
    SomeClass t;
    throw;
} catch( ...) {
    // t destroyed
    // c valid
}



回答2:


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.




回答3:


Yes. When you leave a scope (whether normally or via exception) objects local to that scope are destroyed. This is the basic fact that makes RAII/SBRM work.



来源:https://stackoverflow.com/questions/28588671/c-if-an-exception-is-thrown-are-objects-that-go-out-of-scope-destroyed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!