Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a scope for lambda function in C++11 (delegates)

I'm currently working on a GUI for my C++11/OpenGL3.3 project and I though about making some kind of callback system for interactive GUI elements. I used JS/jQuery and I really liked system of definig in-place methods like onMouseOver, onClick for each website element i wanted. I found that delegates are the best way for me to get such feature.

Example code:

class Button {
    public:
        // ...

        // method (not needed in real-life, just to "show" it)
        void MouseOver(int x, int y) { onMouseOver(this, x, y); }

        // variable
        std::function<void(Button*, int, int)> onMouseOver;
}

void someFunction(...) {
    // ...
    Button t = new Button(...);
    t.onMouseOver = [](Button* this, int x, int y) -> void { some_code_here };
    // ...
}

Main question:

But i'm worried about scope of that particular onMouseOver function that i just created - will that pointer be valid until end of program? Can someone explain what exactly will happen with that function for the rest application lifetime?

Additional questions:

Is there a better way to do something like that? Simpler/more efficient? I've seen many "imposible fast" - is it really that slow?

like image 803
RippeR Avatar asked Dec 12 '25 10:12

RippeR


1 Answers

What is a scope for lambda function in C++11?


According to the standard § 5.1.2/2 & 3 Lambda expressions [expr.prim.lambda]:

2 The evaluation of a lambda-expression results in a prvalue temporary (12.2). This temporary is called the closure object.

3 The closure type is declared in the smallest block scope, class scope, or namespace scope that contains the corresponding lambda-expression.

  • So according to the above, your Lambda function's scope is the scope of function someFunction().

  • However, because you assign it to onMouseOver member variable, its move constructor is evoked, consequently onMouseOver will hold a moved instance of your Lambda.


Will that pointer be valid until end of program?


  • Class template std::function is a general-purpose polymorphic function wrapper (i.e., a function object). Instances of std::function can store, copy, and invoke any callable target (e.g., functions, lambda expressions, bind expressions, or other function objects).

  • Consequently, onMouseOver and its content will be valid as long as the Button class object that contains it is valid.

like image 168
101010 Avatar answered Dec 14 '25 10:12

101010



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!