C++: If an exception is thrown, are objects that g

2019-02-24 23:48发布

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

3条回答
再贱就再见
2楼-- · 2019-02-25 00:08

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.

查看更多
forever°为你锁心
3楼-- · 2019-02-25 00:16

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.

查看更多
一夜七次
4楼-- · 2019-02-25 00:25

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
}
查看更多
登录 后发表回答