Sign in to follow this  
bpoint

order of destruction of objects on the stack

Recommended Posts

bpoint    464
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'?

Share this post


Link to post
Share on other sites
Sharlin    864
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this