user4541498
user4541498

Reputation:

C++ Lambda capture private class member

Here is a part of my Class:

//...
        bool dump_dvars()
        {
            fstream& refvar{ output_file };

            for_each(_array_start, _array_start + *_array_size,
                [&refvar](const void* dvar) -> void
            {
                //work with output_file
            });

            return true;
        }

    private:
        void** _array_start;
        unsigned int* _array_size;
        fstream output_file;
    };

I want to access the private member variable output_file of my Lambda, which is in the public member function dump_dvars. When I capture the this pointer I can not access the variable because it is private, I also don't want to make it public though! I already read this question (How to make the lambda a friend of a class?) but I don't want to create another function. So my current fix for the problem is creating a reference to the private member and pass that variable via reference capture list to my Lambda.

Is that a good solution and good style or is there a better solution?

Upvotes: 25

Views: 19198

Answers (1)

Marouane Fazouane
Marouane Fazouane

Reputation: 1329

You should capture 'this' in the lambda.

The following code compiles and works just fine with g++, clang, VS2010 and VS2013.

#include <iostream>

class A
{
public:
    A() : x(5){}
    void f() const
    {
        ([this]()
        {
            std::cout << x << std::endl;
        })();
    }
private:
    int x;
};

int main()
{
    A a;
    a.f();
}

Upvotes: 25

Related Questions