Crashing when accessing class within lambda



  • Hello,
    I would need some help to understand lambda functions. I get inconsistent SegFaults : when ran in GDB, my program always crashes. When ran outside of GDB, it sometimes works.
    Here is my code :

    connect(pathButton, &QPushButton::pressed, this,
    [=, &optimiser](){
            QString dir = QFileDialog::getExistingDirectory(this, "Open Directory", optimiser.getmodPath(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
            modpathTextEdit->setPlainText(dir);
            optimiser.setModPath(dir);
        });
    

    If I remove optimiser.getmodPath(), it doesn't crash.

    QString Optimiser::getmodPath() const
    {
        return modPath;
    }
    

    It shouldn't be necessary, but here is my full code.

    Thanks.


  • Lifetime Qt Champion

    Hi and welcome to the forums
    I could not spot same code in gitlab ?

    I was wondering if the optimiser you capture by reference will stay in scope ?



  • Sorry, I linked the wrong branch. It is here.

    The optimiser is declared in mainWindow, so it should stay in scope as far as I know.


  • Lifetime Qt Champion

    @G_ka
    Hi
    Aha :)
    It seems to be defined as a local variable in constructor

    MainWindow::MainWindow()
    {
    Optimiser optimiser("C:/", mw_log); // local variable

    so since you capture it with reference, it will point to a deleted variable as
    constructor has run and finished once you press button.

    Put it as a class member of MainWindow (in .h )
    and it will work fine.


  • Moderators

    @G_ka
    as an additional note,

    you can give your connect statement an 4th parameter, for example optimiser, if it's an QObject-derived class -

    Thatway the connection will get resolved when either the sender object(pathButton) or the reference object becomes invalid (optimiser).

    connect(pathButton, &QPushButton::pressed,  &optimiser,
    [=, &optimiser](){
            QString dir = QFileDialog::getExistingDirectory(this, "Open Directory", optimiser.getmodPath(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
            modpathTextEdit->setPlainText(dir);
            optimiser.setModPath(dir);
        });
    


  • Thank you, it worked. @J-Hilk I'll remember it.

    Now, I have another issue. When I append anything to the log, like here, I crash.

    It isn't related to Qt tho, and I probably should be able to fix it by myself. Thanks for the help already.

    Edit : I've fixed it, I was giving the argument before it was initialized.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.