卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章79097本站已运行4412

C++ Lambda 表达式中 this 指针的使用场景

场景:在 c++++ lambda 表达式中使用 this 指针,可以访问成员函数和数据、捕获 this 指针。具体情况:访问成员函数:lambda 表达式可以通过 this 指针调用作用域中对象的成员函数。访问成员数据:lambda 表达式可以通过 this 指针访问作用域中对象的成员数据。捕获 this 指针:lambda 表达式可以通过显式捕获项捕获 this 指针,使 lambda 表达式在作用域结束后仍可访问 this 指针。

C++ Lambda 表达式中 this 指针的使用场景

在 C++ Lambda 表达式中使用 this 指针的场景

引言

在 C++ 中,lambda 表达式允许在函数调用处定义匿名函数。与普通函数不同,lambda 表达式可以访问外部作用域中的变量,包括 this 指针。这使得使用 this 指针在 lambda 表达式中有用。

立即学习“C++免费学习笔记(深入)”;

使用场景

以下是使用 this 指针在 lambda 表达式中的常见场景:

  1. 访问成员函数:lambda 表达式可以使用 this 指针访问作用域中对象的成员函数。例如:
class MyClass {
public:
    int value;

    void multiply(int factor) {
        [this](int x) { value *= x; }(factor);
    }
};
  1. 访问成员数据:lambda 表达式可以使用 this 指针访问作用域中对象的成员数据。例如:
class MyClass {
public:
    int value;

    void printValue() {
        [this] { cout << value << endl; }();
    }
};
  1. 捕获 this 指针:lambda 表达式可以通过显式捕获项来捕获 this 指针,这可以让 lambda 表达式在作用域结束后仍可以访问 this 指针。例如:
class MyClass {
public:
    int value;

    void saveValue() {
        auto capturedThis = [this] { return value; };
    }
};

实战案例

以下是一个使用 lambda 表达式和 this 指针的实战案例:

struct Foo {
    int x;

    void doSomething() {
        int y = 5;
        [this, &y](int z) {
            cout << x + y + z << endl;
        }(10);
    }
};

在这个示例中,lambda 表达式捕获了 this 指针和变量 y 的引用。这使得 lambda 表达式可以访问 this 指针中的 x 成员变量和外部作用域中的 y 变量。

卓越飞翔博客
上一篇: Golang 函数性能的未来趋势是什么?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏