samedi 26 mai 2018

Is a const reference bound to a temporary which is cast to const reference a dangling reference?

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

Aucun commentaire:

Enregistrer un commentaire