We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
在 ”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;
}`
The text was updated successfully, but these errors were encountered:
No branches or pull requests
在 ”C++11常用新特性(二)“ 章节中,说道:
`class Filter
{
public:
Filter(int divisorVal):
divisor{divisorVal}
{}
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;
}`
The text was updated successfully, but these errors were encountered: