I was shown the following example in chat:
#include <iostream>
struct foo { ~foo() { std::cout << "destroying!\n"; } };
const foo& func(const foo& a, const foo&) { return a; }
int main()
{
foo x;
const foo& y = func(foo(), x);
std::cout << "main\n";
}
destroying!
main
destroying!
It appears to demonstrate that the lifetime of the foo
temporary is not extended to entirety of main
, even though it gets bound to a ref-to-const
in that scope.
Presumably, then, the lifetime extension only "works once"; that is, it is applied when func
's arguments are initialised, but isn't passed on through consecutive bindings.
Is my interpretation correct? If so (and if any individual paragraph is directly applicable) what's the standard wording that defines this behaviour?