Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 893
Darryl Jordan Avatar asked Dec 07 '25 17:12

Darryl Jordan


1 Answers

In std::move(Foo()); the Foo object is bound to the parameter of the move-function, not to baz.

And when the function returns, the temporary is destroyed.

like image 116
BoP Avatar answered Dec 09 '25 19:12

BoP