Below is the code snippet:
#include <iostream>
using namespace std;
struct B{
int b;
~B(){cout <<"destruct B" << endl;}
};
B func(){
B b;
b.b = 1;
return b;
}
int main(){
const B& instance = (const B&)func(); //is `instance` a dangling reference?
cout <<instance.b<<endl;
return 0;
}
in this online compiler the output is
destruct B
destruct B
1
So the return value seems to destruct earlier than the cout
operation. So the instance
seems to be a dangling reference.
If we change const B& instance = (const B&)func();
to const B& instance =func();
, then the result is
destruct B
1
destruct B
As a supplement, if I test the code in vs2015, then the output is the last one. However, if tested in gcc(before 4.6) ,the output is the former one,but latter one in version after 4.6. So I want to know whether the online compiler is wrong or the reference is dangling in fact.
According to the newest draft [class.temporary]/6 (irrelevant part is elided by me):
Your code is well-formed.
Before C++14, the wording in the standard is unclear about such case, and there is a defect issue 1376. This issue clarifies the lifetime of the temporary object should not be extended in such case. However, this clarification is superseded by issue 1299 (whose resolution is not included even in C++17, but in the current draft).
So you can conclude that before the resolution of issue 1299, it is a bug for GCC with version after 4.6. There is also a bug report 52202 for GCC.