Is it valid for a lambda to, essentially, close over itself?

前端 未结 1 497
野趣味
野趣味 2020-12-05 02:01

Is this lambda recursion valid?

#include 
#include 

int main() {
   std::function g = [&g](int k) {
           


        
相关标签:
1条回答
  • 2020-12-05 02:23

    At the point at which you capture g by reference, it has been declared, so the name is available for use:

    3.3.2/1 The point of declaration for a name is immediately after its complete declarator (Clause 8) and before its initializer

    You are allowed to use objects in limited ways before they are initialised - basically, anything that doesn't depend on the value is OK:

    3.8/6 before the lifetime of an object has started but after the storage which the object will occupy has been allocated [...] any glvalue that refers to the original object may be used but only in limited ways. [...] using the properties of the glvalue that do not depend on its value is well-defined.

    So by my understanding, what you are doing is well-defined.

    (Although, being ultrapedantic, I don't think it's specified when the storage for an automatic object is allocated, and 8.3.2/5 says that "a reference shall be initialized to refer to a valid object" without defining "valid", so there's scope to argue that it's not well-defined).

    0 讨论(0)
提交回复
热议问题