std::move 和临时对象的生命周期

Dar*_*dan 19 c++ destructor lifetime move-semantics stdmove

有人能解释一下这段代码的执行顺序吗?

struct Foo {
    ~Foo() {
        std::cout << "1";
    }
};
Run Code Online (Sandbox Code Playgroud)
int main() {
    const Foo& bar = Foo();
    const Foo& baz = std::move(Foo());
    std::cout << "2";
}
Run Code Online (Sandbox Code Playgroud)

以下代码打印121.

我明白为什么我在 2 之后得到 1,这是因为对象的生命周期绑定到它执行的代码块,而且我也知道右值可以绑定到左值 const 引用,但是为什么立即调用移动对象的析构函数?这是什么原因呢?这个析构函数到底在哪里被调用?

BoP*_*BoP 13

std::move(Foo());对象中Foo绑定到移动函数的参数,而不是绑定到baz

当函数返回时,临时对象被销毁。


Ale*_*lex 12

std::move有一个t绑定到纯右值的转发引用参数Foo()。然后,当该函数返回时,该临时对象将被销毁,从而为我们提供上述输出。

本质上,临时绑定到参数t而不是baz

//-------------------------------------------------------------------v------------> Foo() is bound to this parameter 
template< class T > constexpr std::remove_reference_t<T>&& move( T&& t ) noexcept;
Run Code Online (Sandbox Code Playgroud)