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?
std::move(Foo())
(a.k.a.static_cast<Foo&&>(Foo())
is not a temporary object; binding a const reference to it does not extend its lifetime. An rvalue reference is not the same thing as an rvalue.baz
being unused, while not complaining aboutbar
since destruction has side-effects, which is an indirect clue, but not a good explanation :(