order of destruction of objects on the stack

Started by
2 comments, last by Falken42 16 years, 11 months ago
Hello all, Are objects declared on the stack *guaranteed* to be destroyed in the reverse order that they are declared? For example, if I have the following classes:
class Foo {
public:
    void func();
};

class Bar {
private:
    Foo *foo;

public:
    Bar(Foo *f) : foo(f) { }
    ~Bar() { foo->func(); }
};
And the following function:
void hoge()
{
    Foo f;
    Bar b(&f);
}
Is this dangerous? Is there any possibility that 'f' will be destroyed before 'b'?
Advertisement
Quote:Original post by bpoint
Are objects declared on the stack *guaranteed* to be destroyed in the reverse order that they are declared?


Yes. Also, class member variables and base class subobjects are guaranteed to be destroyed in the reverse order that they were created.
Reverse order of creation.

http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.2
Excellent, just what I was looking for.

Thanks!

This topic is closed to new replies.

Advertisement