简体   繁体   English

C ++延长&&的寿命

[英]C++ extending lifetime of &&

In the following example: 在以下示例中:

http://coliru.stacked-crooked.com/a/7a1df22bb73f6030 http://coliru.stacked-crooked.com/a/7a1df22bb73f6030

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)(); 为什么d.test2(10)(); work? 工作?

Should it really work, or thats just my undefined behavior equals correct result? 它应该真正起作用,还是仅是我未定义的行为等于正确的结果?

PS 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; PS阅读此内容后,我只能看到一种解释:在(2)中,临时生命周期延长到表达式的结尾,并且在相同的表达式中使用&& crteation进行调用; while (1) actually consists from 2 expressions: 而(1)实际上由2个表达式组成:

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? 是这样吗

A temporary object lasts until the end of the line (well, full expression) where it is created, unless the lifetime is extended. 临时对象会一直持续到创建它的的末尾(完整表达式),除非延长了生存期。

Your code does not extend the lifetimes of any temporaries. 您的代码不会延长任何临时对象的生命周期。 Lifetime extension through binding to references does not "commute", only the first binding extends lifetime. 通过绑定到引用的生命周期扩展不会“通勤”,只有第一个绑定才能扩展生命周期。

So the furst case is UB as you have a dangling reference. 因此,最好的情况是UB,因为您有悬挂的参考。 The referred to temporary goes away st the end of the line: on the next line uou follow the reference, and chaos hapens. 所提到的临时行在行尾消失:在下一行,您跟随引用,并且出现混乱。

In the second case, your reference does not extend the lifetime of the temporary, but the temporary lasts longer than the reference that binds to it does! 在第二种情况下,您的引用不会延长临时项的生存期,但是临时项的持续时间比绑定到它的引用要长! They both die at the end of the line, in reverse order of construction. 它们都以相反的顺序在生产线的末端死亡。

So the call works. 这样通话就可以了。

Should it really work, or thats just my undefined behavior equals correct result? 它应该真正起作用,还是仅是我未定义的行为等于正确的结果?

Seems like it. 看起来是这么回事。 In the example you linked, you have these warnings: 在您链接的示例中,您具有以下警告:

warning: '<anonymous>' is used uninitialized in this function [-Wuninitialized]

Uninitialized objects have indetermine values, and trying to access those values results in undefined behavior. 未初始化的对象具有不确定的值,尝试访问这些值会导致未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM