简体   繁体   中英

Does passing lambdas violate encapsulation when they use a private member variable?

I wrote a function to pass to a third party's class. A static function worked fine until the function needed access to a private member variable to do its work. I can do that using a lambda expression (given that it is converted to std::function either automatically or by casting).

Example:

void classA::doingThings()
{
...
    classB::needsHelpToDoAThing(
    [&](std::type foo) -> size_t { return myFunction(foo); }
    );
...
}

size_t class::myFunction(type foo){
...
type someVar = m_somePrivateMember ...(some work)
...
}

But I don't really understand what I'm doing. Now this other class is using private member variables from a different class. Doesn't this violate encapsulation? Is this a hack or am I missing/misunderstanding a concept?

Encapsulation is the idea that other code doesn't get to poke around in your innards willy-nilly.

Here you created a helper function that can poke around in your innards. This helper function is part of your innards, even if you pass it to someone else.

This no more breaks encapsulation than a member method accessing private data. While it isn't part of the interface of the class explicitly, it is still part of the implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM