lamda表达式
如果选择[=],打印的是正确的值.
在函数中调用lamda表达式时,选用值传递能获取当次的外部值
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPushButton>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
init(1);
init(2);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::init(int row)
{
QPushButton *p;
if(row == 1)
{
p = new QPushButton("button1", this);
} else if(row == 2)
{
p = new QPushButton("button2", this);
p->setGeometry(300, 0 ,100, 40);
}
connect(p, &QPushButton::clicked, [=](){
qDebug() << row;
});
}
如果选择的是[&],打印的值已经释放
关于lamda表达式用于递归的注意项
如果是lamda用自动推导,也就是其基本类型表示,是无法用于递归的,C++23才解决这个问题 如果需要使用递归,需要用std::function<> 去接收lamda,这样是可以用递归的
关于调用库函数的lamda表达式 2025-9-22
// runtest是库函数,如果是用&那么成员变量isStop不会改变,=会改变
// mytest是自身的成员函数,& = 都会检测到改变
std::thread thread([&](){
runtest(isStop);
//mytest(isStop);
});
thread.detach();
部分代码
void MainWindow::on_pushButton_clicked()
{
std::thread thread([=](){
//runtest(isStop);
mytest(isStop);
});
thread.detach();
}
void MainWindow::on_pushButton_2_clicked()
{
isStop.store(true);
}
void MainWindow::mytest(std::atomic<bool>& iss)
{
for(int i = 0; i <= 100000000; i++) {
if(iss.load() == true) {
break;
}
qDebug() << i;
QThread::sleep(1);
}
}
// 库中的函数
void runtest(std::atomic<bool>& isStop)
{
for(int i = 0; i <= 100000000; i++) {
if(isStop.load() == true) {
break;
}
qDebug() << i;
QThread::sleep(1);
}
}