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 aa = 7;
: https://godbolt.org/z/n7vGT44Y5 .
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.