[英]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). 我可以使用lambda表达式来做到这一点(假设它可以自动或通过强制转换为std :: function)。
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? 这是hack吗,还是我缺少/误解了一个概念?
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. 虽然它不是明确地属于类的接口的一部分,但仍是实现的一部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.