mfsiega
mfsiega

Reputation: 2872

Are local objects guaranteed to outlive temporary arguments? (C++11)

If I have a setup where a function takes an object Bar as an argument, passes that object to a local class Foo, and Foo uses the Bar in its destructor such as:

class Foo {
    public:
        Foo(const Bar& bar) : bar_(bar) {}
        ~Foo() {
            bar_.DoSomething();
        }
    private:
        const Bar& bar_;
};

void example_fn(const Bar& input_bar) {
    Foo local_foo(input_bar);
    // ... do stuff.
    // When foo goes out of scope, its destructor is called, using input_bar.
}

If example_fn is called with a temporary Bar input_bar, is the local variable Foo local_foo guaranteed to be destroyed before the temporary argument? In other words, are arguments guaranteed to outlive local variables?

Upvotes: 2

Views: 247

Answers (1)

WhiZTiM
WhiZTiM

Reputation: 21576

is the local variable Foo local_foo guaranteed to be destroyed before the temporary argument?

Yes, Objects with automatic storage duration (aka locals) are guaranteed to be destroyed in the reverse order of construction. The function arguments are always constructed (in an unspecified order) before the locals within the block scope. See Object Destruction in C++

[class.temporary/5]

5: ...In addition, the destruction of temporaries bound to references shall take into account the ordering of destruction of objects with static, thread, or automatic storage duration ([basic.stc.static], [basic.stc.thread], [basic.stc.auto]); that is, if obj1 is an object with the same storage duration as the temporary and created before the temporary is created the temporary shall be destroyed before obj1 is destroyed; if obj2 is an object with the same storage duration as the temporary and created after the temporary is created the temporary shall be destroyed after obj2 is destroyed. ...

Upvotes: 7

Related Questions