Can a C++ lambda constructor argument capture the constructed variable?

后端 未结 2 1690
庸人自扰
庸人自扰 2021-02-19 23:13

The following compiles. But is there ever any sort of dangling reference issue?

    class Foo {
         Foo(std::function fn) { /* etc         


        
2条回答
  •  广开言路
    2021-02-20 00:16

    But is there ever any sort of dangling reference issue?

    That depends entirely on what you're doing with Foo. Here's an example that would have dangling reference issues:

    struct Foo {
         Foo() = default;
         Foo(std::function fn) : fn(fn) { }
         std::function fn;
    }
    
    Foo outer;
    {
        Foo inner([&inner](int i){f(i, inner);});
        outer = inner;
    }
    outer.fn(42); // still has reference to inner, which has now been destroyed
    

提交回复
热议问题