Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lambda使用错误:章节”C++11常用新特性(二)“ #6

Open
achilsh opened this issue Mar 5, 2022 · 0 comments
Open

lambda使用错误:章节”C++11常用新特性(二)“ #6

achilsh opened this issue Mar 5, 2022 · 0 comments

Comments

@achilsh
Copy link

achilsh commented Mar 5, 2022

在 ”C++11常用新特性(二)“ 章节中,说道:
`class Filter
{
public:
Filter(int divisorVal):
divisor{divisorVal}
{}

std::function<bool(int)> getFilter() 
{
    return [=](int value) {return value % divisor == 0; };
}

private:
int divisor;
};`

这个类中有一个成员方法,可以返回一个lambda表达式,这个表达式使用了类的数据成员divisor。而且采用默认值方式捕捉所有变量。你可能认为这个lambda表达式也捕捉了divisor的一份副本,但是实际上并没有。因为数据成员divisor对lambda表达式并不可见,你可以用下面的代码验证:*******.


我验证过了, [=] 能捕获到 类数据成员,比如下面没问题:
`#include
#include

using namespace std;

class Demo {
public:
Demo():m_i(100) {}
virtual ~Demo() {}

void func(int x) {
auto f1 = [=]{ std::cout << &m_i << std::endl; return m_i + x; };
std::cout << f1() << std::endl;
std::cout << &m_i << std::endl;
}
std::function<int(int)> getFunc() {
return [=](int val) { return val + m_i; };
}
void setData(int d) {
m_i = d;
}

private:
int m_i;
};

int main() {
Demo d;
d.func(10);
std::function<int(int)> ff;
{
Demo dd;
ff = dd.getFunc();
dd.setData(400);
}
std::cout << "-------" << std::endl;
//
std::cout << ff(200) << std::endl;
return 0;

}`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant