jeudi 22 juillet 2021

Returning a reference to an implicitly constructed parameter vs an implicitly constructed internal object

C++11 question

Trying to understand an issue I came across in our code. Not looking for the "right" way to do this, just want to know how this is supposed to work so I can figure out how to fix things in the future

I think function f1() is fine returning a reference to the temp implicitly constructed on the same line as the p1

But what about p2? The temp is constructed implicitly in the body of f2() when calling f1(), but f2() is returning the reference that is being returned by f1(). I thought the lifetime of the temp is extended to match the lifetime of the reference

asking because in one of our compilers p2 is garbage on the next time, but on the others it is not

struct PP
{
    int i;
    PP(int i_) : i(i_) {}
};


const PP &f1(const PP &p) 
{
 return p; 
}

const PP &f2(int i) 
{
 return f1(i); 
} // does the temp live here after return?

int main()
{
    const PP &p1 = f1(1);
    const PP &p2 = f2(2);  // is p2 valid on the NEXT line
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire