Lambdas and capture by reference local variables : Accessing after the scope

后端 未结 3 640
一向
一向 2020-12-03 17:39

I am passing my local-variables by reference to two lambda. I call these lambdas outside of the function scope. Is this undefined ?

std::pair<         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 17:59

    Unfortunately C++ lambdas can capture by reference but don't solve the "upwards funarg problem".

    Doing so would require allocating captured locals in "cells" and garbage collection or reference counting for deallocation. C++ is not doing it and unfortunately this make C++ lambdas a lot less useful and more dangerous than in other languages like Lisp, Python or Javascript.

    More specifically in my experience you should avoid at all costs implicit capture by reference (i.e. using the [&](…){…} form) for lambda objects that survive the local scope because that's a recipe for random segfaults later during maintenance.

    Always plan carefully about what to capture and how and about the lifetime of captured references.

    Of course it's safe to capture everything by reference with [&] if all you are doing is simply using the lambda in the same scope to pass code for example to algorithms like std::sort without having to define a named comparator function outside of the function.

    An approach that can work sometimes is capturing by value a shared_ptr to a heap-allocated state. This is basically implementing by hand what Python does automatically (but pay attention to reference cycles to avoid memory leaks: Python has a garbage collector, C++ doesn't).

提交回复
热议问题