Home > Software design >  Accessing private member function via Lambda
Accessing private member function via Lambda

Time:03-29

In a project, I have a C-API which uses C-style function pointers as callbacks. In one of those callbacks, I need to access a private function of an object Foo. Note that the API-call is done within a function of my class. Because of not shown code, I have a handle to my object as a void* accessible to me.

Things aside that the construct is prone to errors, by passing a lambda as callback I am able to access the private function of my object. This is somewhat unexpected but welcome to me. I haven't found anything regarding this behavior, so I would kindly ask if somebody could shed some light why this is actual working. I am not aware that the lambda is catching something, but it appears that is has something to do with the actual scoping. I am using C 17 and gcc 10.2.

Here's a sample block of code:

void TestFunc(void (*)(void*)) {
}

class Foo {
public:
    Foo() {
     TestFunc([](void* handle){
         auto foo = reinterpret_cast<Foo*>(handle);
         foo->BarFunc();
     });
    };
private:
    void BarFunc() {};
};

CodePudding user response:

Your code is working because Standard allows it. So first we have this (C 20 [expr.prim.lambda.closure]p2):

The closure type is declared in the smallest block scope, class scope, or namespace scope that contains the corresponding lambda-expression. <...>

And in your example we have a block scope so in the end we have an unnamed local class declaration and according to [class.local]p1:

A class can be declared within a function definition; such a class is called a local class. The name of a local class is local to its enclosing scope. The local class is in the scope of the enclosing scope, and has the same access to names outside the function as does the enclosing function

  • Related