C++17 关键新特性介绍及代码讲解 (7) --- lambda capture of ‘*this‘ by value

本文介绍了C++17的关键新特性——lambda表达式捕获*this按值,通过实例展示了如何避免引用陷阱,提高异步编程的安全性。C++17之前的lambda捕获只能按引用访问对象成员,而C++17引入的新方式允许按值复制对象,使得在lambda内部访问的成员变量值不会因外部对象状态变化而改变。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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(
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值