Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 898
mczarnek Avatar asked Feb 18 '15 16:02

mczarnek


3 Answers

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
}
like image 105
4pie0 Avatar answered Oct 30 '22 17:10

4pie0


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.

like image 31
Cory Kramer Avatar answered Oct 30 '22 17:10

Cory Kramer


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.

like image 41
Jerry Coffin Avatar answered Oct 30 '22 16:10

Jerry Coffin