C ++ Lambda捕获私有类成员

时间:2023-01-15 15:27:17

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.

我想访问我的Lambda的私有成员变量output_file,它位于公共成员函数dump_dvars中。当我捕获这个指针时,我无法访问该变量,因为它是私有的,我也不想让它公开!我已经读过这个问题(如何让lambda成为一个类的朋友?)但我不想创建另一个函数。所以我目前解决的问题是创建对私有成员的引用,并通过引用捕获列表将该变量传递给我的Lambda。

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

这是一个很好的解决方案和良好的风格还是有更好的解决方案?

1 个解决方案

#1


You should capture 'this' in the lambda.

你应该在lambda中捕获'this'。

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

以下代码编译并适用于g ++,clang,VS2010和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();
}

#1


You should capture 'this' in the lambda.

你应该在lambda中捕获'this'。

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

以下代码编译并适用于g ++,clang,VS2010和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();
}