question on the order in which objects created on the stack getdestroyed

Y

Yan

Can I rely on the order in which destructors for objects 'a' and 'b'
are called in the attached code or it's up to the compiler to decide?

Thank you.

-------------------
class A {};
class B {};

void f() {
A a;
B b;
}
-------------------
 
A

Andrey Tarasevich

Yan said:
Can I rely on the order in which destructors for objects 'a' and 'b'
are called in the attached code or it's up to the compiler to decide?

Thank you.

-------------------
class A {};
class B {};

void f() {
A a;
B b;
}
-------------------

Yes. In C++ static and automatic objects are destroyed in the reverse
order of their creation.
 
A

Andrey Tarasevich

Jeff said:
Given that they are in the same translation unit.

No. The global order or destruction is always the reverse of the global
order of construction, whatever the latter might be. It is true that the
order of construction [of static objects] is not specified across
translation units, but once some (any) global construction order took
place during the actual execution of the program, the order of
destruction is required to be the exact reverse of it. Globally, i.e.
across all translation units.
 
A

Andrey Tarasevich

Jeff said:
No. The global order or destruction is always the reverse of the
global order of construction, whatever the latter might be. It is true
that the order of construction [of static objects] is not specified
across translation units, but once some (any) global construction
order took place during the actual execution of the program, the order
of destruction is required to be the exact reverse of it. Globally,
i.e. across all translation units.

D'oh. I stand corrected. Do you know where the standard covers this?
I'm having a little trouble finding it.

I believe "3.6.3 Termination" covers it in the very first paragraph.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top