Liu Nick
Liu Nick

Reputation: 369

Why the body of my lambda expression in member function is not executed?

Recently I have been studying lambda expressions and following lambda code surprises me:

#include <iostream>

class lambda_this_test
{
private:
    int mNumber;
public:
    lambda_this_test()
    {
        mNumber = 11;
    };
    void print_member()
    {
        //lambda expression
        [this]{mNumber = 12; std::cout<< "mNumber = \n"<<mNumber<<std::endl;};
    }
};

int main()
{
    lambda_this_test testClass;

    testClass.print_member();
}

When executed, no prints can be seen so that it seems body of the lambda expression is not executed at all, and then I use gdb to prove this because there is no code in print_member() function.

May I ask what's wrong with my usage of lambda?

Upvotes: 2

Views: 304

Answers (2)

Piotr Skotnicki
Piotr Skotnicki

Reputation: 48447

It looks that you have forgotten to execute your lambda expression; you should add parens:

[this]{mNumber = 12; cout<< "mNumber = \n"<<mNumber<<endl;} ();
//                                                          ^^

That is, the below statement:

[this]{mNumber = 12; cout<< "mNumber = \n"<<mNumber<<endl;};

only declares a lambda expression. Alternatively, you could write:

auto lambda = [this]{mNumber = 12; cout<< "mNumber = \n"<<mNumber<<endl;};

lambda();

Upvotes: 11

Liu Nick
Liu Nick

Reputation: 369

thanks Piotr S, this is clear now. Lambda expression is to declare the closure object. and body of lambda expressin is inside the operator() of that closure object, so if the body need to be executed, then operator() shoud be invoked.

Upvotes: 0

Related Questions