本地对象是否保证比临时参数长寿? (C++11)

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

如果我有一个函数将对象 Bar 作为参数的设置,将该对象传递给本地 class Foo,并且 Foo 使用Bar 在其析构函数中,例如:

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

如果用临时Bar input_bar调用example_fn,局部变量Foo local_foo是否保证在临时参数之前销毁?换句话说,参数是否保证比局部变量长?

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

是的,具有自动存储持续时间的对象(又名本地对象)保证以相反的构造顺序销毁。函数参数总是在块范围内的局部变量之前构造(以未指定的顺序)。参见 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. ...