5-C++中的lambda
·
函数指针
函数指针是C/C++等语言中一种特殊的指针,它指向函数而不是数据。
函数指针存储的是函数的入口地址,通过这个指针可以调用相应的函数。
返回类型 (*指针变量名)(参数类型列表);
int (*pFunc)(int, int);
int add(int a, int b) {
return a + b;
}
pFunc = add; // 将函数add的地址赋给pFunc
int result1 = pFunc(3, 4); // 方式1:像调用函数一样使用指针
int result2 = (*pFunc)(3, 4); // 方式2:解引用指针后调用
- 回调函数:函数指针常用于实现回调机制。例如,在事件驱动编程、排序函数中指定比较函数等。例如,C标准库中的qsort函数就使用函数指针来指定比较函数:
void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *));
仿函数
仿函数本质上是一个
类或结构体,它重载了 () 运算符,使得该类的对象可以像函数一样被调用。
#include <iostream>
class MyFunctor {
public:
// 重载函数调用运算符
int operator()(int a, int b) {
return a + b;
}
};
int main() {
MyFunctor adder; // 创建一个仿函数对象
int result = adder(3, 4); // 像函数一样调用
std::cout << "3 + 4 = " << result << std::endl;
return 0;
}
- 仿函数与普通函数相比,本质上是类,
仿函数对象能够在多次调用之间保持和修改内部数据(状态持有) - 仿函数与函数指针相比,仿函数通常是内联的,性能更好
lambda表达式
C++中指针的对象化处理:
- 智能指针对指针进行对象化处理,通过对象的生命周期管理指针的生命周期
- lambda表达式对函数指针进行对象化处理,通过对象可以使函数指针访问函数外的变量
格式
[捕获列表] (形参列表) mutable? constexpr? -> 返回类型{
函数体;
};
捕获列表 (capture-list)
- [] 不捕获任何外部变量
- [x, &y] 按值捕获x,按引用捕获y
- [&] 隐式按
引用捕获所有外部变量 - [=] 隐式
按值捕获所有外部变量 - [this]
捕获当前类的this指针,在类的成员函数内部 - [=, &x] 默认按值捕获,但x按引用捕获
- [&, x] 默认按引用捕获,但x按值捕获
关键在于确保lambda的生命周期不会超过其捕获的对象,通常通过智能指针或明确的生命周期管理来实现
按引用捕获 和 捕获this指针 的情况容易出现lambda生命周期超过捕获对象的问题。
原理

捕获 this 指针的风险
主要风险:悬空指针
class Processor {
int data = 100;
public:
std::function<int()> createTask() {
return [this]() {
return data; // 危险:可能访问已销毁的对象
};
}
};
void problem() {
std::function<int()> task;
{
Processor p;
task = p.createTask(); // task可以通过p的this指针访问p的data变量
} // Processor的对象 p 被销毁
int result = task(); // 未定义行为!访问已销毁的对象
}
std::function<int()> task; 定义了一个:
-
通用的函数包装器
std::function -
存储无参数、返回int的可调用对象
int()
解决方案
1. 使用智能指针 (推荐)
class Processor : public std::enable_shared_from_this<Processor> {
int data = 100;
public:
std::function<int()> createSafeTask() {
auto self = shared_from_this();
return [self]() {
return self->data; // 安全的共享所有权
};
}
};
2. 值捕获所需数据
class Processor {
int data = 100;
public:
std::function<int()> createSafeTask() {
int local_data = data; // 复制数据
return [local_data]() {
return local_data; // 安全的访问副本
};
}
};
3. C++17 按值捕获 *this
class Processor {
int data = 100;
public:
std::function<int()> createSafeTask() {
return [*this]() mutable { // 复制整个对象
return data;
};
}
};
生命周期管理最佳实践
#include <memory>
#include <functional>
class SafeProcessor {
std::shared_ptr<int> data = std::make_shared<int>(100);
public:
std::function<int()> createTask() {
auto local_data = data; // 延长生命周期
return [local_data]() {
return *local_data; // 始终有效
};
}
// 弱引用版本,避免循环引用
std::function<std::optional<int>()> createWeakTask() {
std::weak_ptr<int> weak_data = data;
return [weak_data]() -> std::optional<int> {
if (auto shared_data = weak_data.lock()) {
return *shared_data;
}
return std::nullopt; // 对象已销毁
};
}
};
Lambda 表达式的作用
主要作用:
- 简化代码:避免为简单操作编写独立的函数或函数对象
- 就地定义:在需要的地方直接定义函数逻辑
- 捕获上下文:可以访问外部变量,减少参数传递
- 函数式编程:支持函数作为参数传递和返回
C++各个版本 对 Lambda 的改进
C++11 - 基础功能
auto lambda = [](int x) -> int { return x * 2; };
C++14 - 重要增强
// 泛型lambda
auto lambda = [](auto x) { return x * 2; };
// 初始化捕获
auto lambda = [value = 42]() { return value; };
// 返回类型推导
auto lambda = [](int x) { return x * 2; }; // 自动推导返回类型
C++17 - 进一步改进
// constexpr lambda
constexpr auto lambda = [](int n) { return n * n; };
static_assert(lambda(5) == 25);
// 在常量表达式中使用
std::array<int, [](int x) { return x + 1; }(5)> arr;
C++20 - 重大升级
// 模板参数列表
auto lambda = []<typename T>(T t) { return t; };
// 可默认构造和可赋值(无状态lambda)
auto f = []{};
decltype(f) f2; // C++20 OK
// 捕获包扩展
template<typename... Args>
auto make_lambda(Args&&... args) {
return [...args = std::forward<Args>(args)]{};
}
总结
- Lambda 是现代 C++ 的核心特性,极大提升了代码表达力
- 捕获 this 需要特别注意生命周期问题,可能导致悬空指针
- 推荐使用 智能指针或值捕获来确保安全性
- C++17 的
[*this]提供了安全的对象复制方案
class Button {
private:
std::string label;
std::vector<std::function<void()>> clickHandlers;
int clickCount = 0;
public:
void onClick(std::function<void()> handler) {
clickHandlers.push_back(handler);
}
void simulateClick() {
for(auto& handler : clickHandlers) {
handler();
}
}
};
// 弹窗类
class Dialog {
private:
Button* okButton;
Button* cancelButton;
std::string InputString;
public:
void setupButtons() {
// 为按钮设置点击处理函数,需要访问Dialog的成员
okButton->onClick([this]() {
std::cout << "OK clicked with input: " << InputString << std::endl;
saveData();
closeDialog();
});
cancelButton->onClick([this]() {
std::cout << "Cancel clicked. Total operations: " << getOperationCount() << std::endl;
resetDialog();
});
}
private:
void saveData() { /* 保存数据 */ }
void closeDialog() { /* 关闭对话框 */ }
void resetDialog() { /* 重置对话框 */ }
int getOperationCount() { return 5; } // 示例
};
更多推荐

所有评论(0)