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.