Advertisement

Capturing "this" in a lambda function

Started by February 05, 2018 09:59 PM
6 comments, last by MarcusAseth 6 years, 9 months ago

Hi guys, I'm having some trouble understanding what this code is doing, can you give me a hand ?_? 

Code by Vittorio Romeo, you can find the whole thing here

So the part I'm having trouble with is this one:


 // Another useful method will allow the user to execute arbitrary
    // code on all entities of a certain type.
    template <typename T, typename TFunc>
    void forEach(const TFunc& mFunc)
    {
        // Retrieve all entities of type `T`.
        auto& vector(getAll<T>());

        // For each pointer in the entity vector, simply cast the
        // pointer to its "real" type then call the function with the
        // casted pointer, dereferenced.
        for(auto ptr : vector) mFunc(*reinterpret_cast<T*>(ptr));
}

and


 // The game logic is now much more generic: we ask the
                // manager to give us all instances of a certain game
                // object type, then we run the collision functions.
                // This is very flexible as we can have any number
                // of balls and bricks, and adding new types of game
                // objects is extremely easy.
                manager.forEach<Ball>([this](auto& mBall)
                    {
                        manager.forEach<Brick>([this, &mBall](auto& mBrick)
                            {
                                solveBrickBallCollision(mBrick, mBall);
                            });
                        manager.forEach<Paddle>([this, &mBall](auto& mPaddle)
                            {
                                solvePaddleBallCollision(mPaddle, mBall);
                            });
});

I get that forEach<T>(Tfunc) retrieves a vector<BaseClass*>&  ,casts every element in it from the BaseClass pointer to a T* and apply the TFunc passed to them, but I kind of get lost, I mean why the lambda passed to it is capturing [this], and even what is [this] in that context...?!

Is it the Game class that owns the manager data member?

Or 'this' is becoming something else inside the forEach function (meaning that it acts inside of it since is a template argument, capturing the "this" inside of forEach, which I believe should be the manager itself?).

And then, I don't see 'this' used anywhere, so...just very confused. Can you help me understand? ^_^

 

Capturing the this pointer is needed if you want the closure defined by the lambda to access member variables on the class that owns the method that the lambda is defined within. The syntax allows access to member variables and methods on the "enclosing object" without actually using the this pointer - just as if the code within the lambda was in a method on the object.

I haven't looked at the code in detail, but is solvePaddleBallCollision a method on whatever class has the method defining these lambdas?

Advertisement

No that solve functions are standing alone function, but according to what you say the 'this' capture is then needed to access the 'manager.' which is a member variable of the Game class (the code snippet is from a member function of the Game class). Makes sense, thanks :)

Follow up question is, is capturing 'this' the only way or he could have directly captured the member variable needed, in this case 


[&manager](){}

 

I believe you need to capture this if you're capturing by reference. Not sure if that's necessary if you're capturing the member by value.

2 hours ago, Oberon_Command said:

I believe you need to capture this if you're capturing by reference. Not sure if that's necessary if you're capturing the member by value.

You could expose only the member variable as well.


#include <functional>
#include <iostream>

struct Integer {
    int a = 0;
};

int main() { 
    Integer integer;
    int &b = integer.a;
    std::cout << integer.a << std::endl;
    const auto lambda = [&b]() { ++b; };
    lambda();
    std::cout << integer.a << std::endl;
};

In the snippet above, I capture the member variable a by reference in the capture list of the lambda. And of course, an instance of a class can thus in a similar fashion create a lambda with references to certain of its member variables in the capture list without adding this.

🧙

On 2/6/2018 at 1:01 AM, MarcusAseth said:

Follow up question is, is capturing 'this' the only way or he could have directly captured the member variable needed, in this case 



[&manager](){}

Use (referring to my Minimal Working Example above):


struct Integer {
    int a = 0;
    void f() {
        const auto lambda = [&b(a)]() { ++b; };
        lambda();
    }
};

What you propose would not work:


struct Integer {
    int a = 0;
    void f() {
        const auto lambda = [&a]() { ++a; };
        lambda();
    }
};

error: 'this' cannot be implicitly captured in this context

Damn, I thought these two previous posts would be merged :(

So I add a summary:


struct Integer {
    int a = 0;
    void f() {
        const auto lambda = [&b(a)]() { ++b; };
        lambda();
    }
};

int main() { 
    Integer integer;
    int &b = integer.a;
    std::cout << integer.a << std::endl;
    const auto lambda = [&b]() { ++b; };
    lambda();
    std::cout << integer.a << std::endl;
    integer.f();
    std::cout << integer.a << std::endl;
};

Try It Online

🧙

Advertisement

No more doubts left on this point, thanks :)

This topic is closed to new replies.

Advertisement