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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With