I was shown the following example in chat:
#include
struct foo { ~foo() { std::cout << \"destroying!\\n\"; } };
const foo& func(co
Probably I am a bit slow but to me it did not become clear what the resolution of this question is from reading the other answers. Thus I modified the code shown and wanted to summarize for others: the answer is, you get undefined behavior if you access y!
Run this code:
struct foo {
int id;
foo(int id) : id(id) { std::cout << "ctor " << id << std::endl; };
~foo() { std::cout << "dtor " << id << std::endl; }
};
const foo& func(const foo& a, const foo&) { return a; }
int main(int argc, char** argv) {
foo x(1);
const foo& y = func(foo(2), x);
std::cout << "main " << y.id << std::endl;
return 0;
}
The output for me is:
ctor 1
ctor 2
dtor 2
main 2
dtor 1
But the line main 2 is undefined behavior.