Sign in to follow this  

order of destruction of objects on the stack

This topic is 3873 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
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

This topic is 3873 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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