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,这样是可以用递归的

Table of Contents