According to this blog, the following code should be well defined:
#include <iostream>
struct Foo{
Foo()=default;
Foo(Foo && f)=default;
Foo(Foo const& f)=delete;
~Foo(){std::cout << __func__ << '\n';}
//value to bind to
int a=123;
};
int main(){
const int& ptr = Foo{}.a;
std::cout << ptr << '\n';
}
Although Foo{}
creates a temporary, the binding with const&
should prolong Foo
's lifetime.
The temporary should last as long as the reference.
The article states:
Q3: When the reference goes out of scope, which destructor gets called?
A3: The same destructor that would be called for the temporary object. It’s just being delayed.
If that is the case, why does the program print:
~Foo
123
instead of:
123
~Foo
It seems that Foo
is being destructed before I use the reference.