Search code examples
c++destructorlifetimemove-semanticsstdmove

std::move and lifetime of temporary objects


Can someone explain the execution order of this code?

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

The following code prints 121.

I understand why I get 1 after 2, it's because the lifetime of the object is bound to the code block where it executes and I also know that rvalue can bind to an lvalue const reference, but why destructor of the moved object is called immediately? What's the reason for that? Where exactly is this destructor called?


Solution

  • std::move has a forwarding reference parameter t that binds to the prvalue Foo(). Then when that function returns, that temporary is destroyed giving us the mentioned output.

    Essentially the temporary is bound to parameter t instead of baz

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