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

后端 未结 2 1692
庸人自扰
庸人自扰 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:01

    The lambda expression [&foo](int i){f(i, foo);} will lead compiler to generate a closure class something like this (but not totally correct) :

    class _lambda
    {
        Foo& mFoo; // foo is captured by reference
    
    public:
        _lambda(Foo& foo) : mFoo(foo) {}
    
        void operator()(int i) const
        {
           f(i, mFoo);
        }
    };
    

    Therefore, the declaration Foo foo([&foo](int i){f(i, foo);}); is treated as Foo foo(_lambda(foo));. Capturing foo itself when constructing does not has problem in this situation because only its address is required here (References are usually implemented via pointers).

    The type std::function will internally copy construct this lambda type, which means that Foo's constructor argument fn holds a copy of _lambda object (that holds a reference (i.e., mFoo) to your foo).

    These implies that dangling reference issue may arise in some situations, for example:

    std::vector> vfn; // assume vfn live longer than foo
    
    class Foo {
         Foo(std::function fn) { vfn.push_back(fn); }
    }
    
    void f(int i, Foo& foo) { /* stuff with i and foo */ }
    
    Foo foo([&foo](int i){f(i, foo);});
    
    ....
    
    void ff()
    {
        // assume foo is destroyed already,
        vfn.pop_back()(0); // then this passes a dangling reference to f.
    }
    

提交回复
热议问题