21
votes

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?

1
Removed tags, since I don't see a primary relation of the question to windows or visual-studio-2013. - πάντα ῥεῖ
@Tobi_R "...doesn't give me access to the private members" - It doesn't? ? Is this a VS2013 thing? Works for me with both clang and gcc. Can you include the exact error message you're receiving at compile time (in your question please)? - WhozCraig
I am able to access protected an private members in lambda, only VS intellisense doesn't show them in a statement completition. Why is _array_size a pointer? - LogicStuff
Well, apparently I got tricked by IntelliSense as LogicStuff just pointed out. The project I am working on has something to do with reverse engineering and the _array_size pointer is pointing to 4 bytes that seem to hold the size of the array pointed to by _array_start! - user4541498
@WhozCraig I noticed that IntelliSense didn't show the private members, but when I added a public dummy int it showed it. Next time I should probably don't trust IntelliSense and compile first :-) (Sadly πάντα ῥεῖ removed the VS2013 tag from my question) - user4541498

1 Answers

23
votes

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();
}