C++17 关键新特性介绍及代码讲解 (7) — lambda capture of ‘*this’ by value
一句话概括:
在定义 lambda 的 captures 时,可以通过 [*this]
这种形式,将当前 this 所指向的 object,
以 value-copy 的方式拷贝下来,并在 lambda 的表达式中使用拷贝得到的 object 成员变量值。
完整 demo 代码参见 gitee.com 上的公开代码仓库 :
[lambda_capture_of_this_by_value]
对于在一个 non-static 成员函数中声明的 lambda 表达式,如果需要访问当前 object 的成员变量,在 C++17 之前,
我们需要 capture 代表当前对象的 ‘this’ 指针,再通过 ‘this’ 去访问当前 object 的成员变量:有三种 capture 的方式,
即 [=]
、[&]
、[this]
; 但这三种方式,都只能让 lambda 表达式中访问当前 object 的成员变量方式,全都为 by reference,
做不到真正的 by value copy,我们来看一下例子代码:
/* to capture (*this) */
struct S {
S(int i) : m_i(i) {
};
int m_i;
// all of get_a, get_b and get_c, capture (*this) by reference.
auto get_a() {
// implicit capture of (*this) by reference.
auto a = [&] {
return m_i; }; // transformed to (*this).m_i
return a;
}
auto get_b() {
// implicit capture of (*this) by reference, even implicit capture the used automatic variables by copy, i.e. '='.
auto b = [=] {
return m_i; }; // transformed to (*this).m_i
return b;
}
auto get_c() {
// explicit capture of (this) by copy, then capture of (*this) by reference.
auto c = [this] {
return m_i; }; // transformed to (*this).m_i
return c;
}
}
int main(){
// test capture of (*this).
auto s = S(10);
// capture of (*this) by reference in a, b, c.
auto a = s.get_a(