What is the lifetime of a C++ lambda expression?

前端 未结 4 927
长发绾君心
长发绾君心 2020-12-01 02:04

(I have read What is the lifetime of lambda-derived implicit functors in C++? already and it does not answer this question.)

I understand that C++ lambda syntax is j

4条回答
  •  无人及你
    2020-12-01 02:25

    The lifetime is exactly what it would be if you replaced your lambda with a hand-rolled functor:

    struct lambda {
       lambda(int x) : x(x) { }
       int operator ()(int y) { return x + y; }
    
    private:
       int x;
    };
    
    std::function meta_add(int x) {
       lambda add(x);
       return add;
    }
    

    The object will be created, local to the meta_add function, then moved [in its entirty, including the value of x] into the return value, then the local instance will go out of scope and be destroyed as normal. But the object returned from the function will remain valid for as long as the std::function object that holds it does. How long that is obviously depends on the calling context.

提交回复
热议问题