【发布时间】:2018-07-09 20:55:01
【问题描述】:
#include <iostream>
#include <functional>
#include <utility>
using namespace std;
typedef std::function<void(const string&, const string&, const bool, const bool)>
Callback_T;
class A {
public:
void
process(const string &a, const string &b, const bool c, const bool d, const int e)
{
cout << "a: " << a << " b: " << b << " c: " << c << " d: " << d << " e: " << e << endl;
}
Callback_T
constructCallback(const int &e)
{
Callback_T callback =
[&, this, e](auto&&...args) // <--- here, e must be captured by value, why?
{
this->process(
std::forward<decltype(args)>(args)...,
e);
};
return callback;
}
};
int main()
{
A a;
auto cb = a.constructCallback(20);
cb("A", "B", true, false);
}
上述程序输出:“a:A b:B c:1 d:0 e:20” 但是,如果我将捕获 e 的那条线更改为:
[&, 这个, &e]
它输出:“a: A b: B c: 1 d: 0 e: 26340408”,似乎表明 e 没有定义/初始化。
为什么只通过价值来捕捉它?
【问题讨论】:
-
(临时)变量超出范围。
-
只是提醒您:即使是引用也可能会变成 dangling:What is a dangling reference?