Cory Klein
Cory Klein

Reputation: 55620

In what order are local scoped objects destructed?

Will foo be destructed before bar, after bar, or is there no guarantee either way?

myFunction()
{
    Foo foo = Foo();
    Bar bar = Bar();
    return;
}

Upvotes: 2

Views: 665

Answers (3)

user2032040
user2032040

Reputation: 101

The memory of a function is called "the stack". And like every other stack, the last thing you put on, is the first thing you'll take off.

So, effectively, when the function returns and the local memory goes out of scope, all local variables are destructed in reverse order.

That is always the case, and you most definitely can rely on that (within the same thread).

Upvotes: 1

Xperiaz X
Xperiaz X

Reputation: 226

In inheritance it is reverse order. In your case, It is in same order of creation.

 Foo f= new Foo();
 Bar b= new Bar();

f is destroyed before b

Upvotes: -3

lapk
lapk

Reputation: 3918

They are destroyed in the reverse order of their declaration. In

{
 Foo foo = Foo();
 Bar bar = Bar();
}

foo constructed first, then bar. When going out of scope - bar destructed first, then foo.

Upvotes: 7

Related Questions