Reputation: 34
I'm sure this has been asked before, but my googling skills weren't sufficient to find my case. Simply put, is the following valid C++ code?
struct A {
int a;
static A foo() { return {5}; }
A& bar() { return *this; }
A(A&) = delete;
};
int main() {
A& a = A::foo().bar();
a.a = 7;
return a.a;
}
Normally, I should only be allowed to store const references to temporaries, but I'm unsure if C++17 relaxed this. I tried to read the specification, but got confused.
clang, gcc and msvc seem to able to compile this, but gcc breaks with O2 if I remove a.a = 7;
: https://godbolt.org/z/n7vGT44Y5.
Upvotes: 0
Views: 76
Reputation: 217145
bar()
doesn't return temporary, it returns reference.
A::foo()
returns a temporary, its lifetime ends at end of full expression.
so a
is a dangling reference.
Upvotes: 2