In the following example:
struct D{
    int i;    
    auto test2(int&& j){
        return [&](){       // captured by reference!
            cout << i*(j);
        };
    }    
};
int main()
{
    D d{10};
    {
      auto fn = d.test2(10);
      fn();                     // 1. wrong result here
      d.test2(10)();            // 2. but ok here
    }
}
Why does d.test2(10)(); work?
Should it really work, or thats just my undefined behavior equals correct result?
P.S. After reading this I see only one explanation: in (2) temporary lifetime prolongs till the end of the expression, and call happens in the same expression with && crteation; while (1) actually consists from 2 expressions:
a temporary bound to a reference parameter in a function call exists until the end of the full expression containing that function call: if the function returns a reference, which outlives the full expression, it becomes a dangling reference.
Is this the case?
Aucun commentaire:
Enregistrer un commentaire