0

I've attached a code snippet to a C++ program I am working on Qt Creator. The goal of this snippet is to provide the user with a means to enter a custom temperature value and then save this value.

  //custom temp
    QLineEdit *addCustomTemp;
    QLabel *customTemp = new QLabel("Custom temp");
    addCustomTemp = new QLineEdit();

    //QString tempVal = addCustomTemp->text();
    // double tempValDouble = tempVal.toDouble();
    //std::cout << "My temp" << tempValDouble;

    QPushButton *submitButton = new QPushButton("Submit");
    submitButton->setAutoDefault(false);
    double tempValDouble;

    auto handleCustomTemp = [&]() {
          QString tempVal = addCustomTemp->text();
          tempValDouble = tempVal.toDouble();
          qDebug() << "Custom temp:" << tempValDouble;
      };

    connect(submitButton, &QPushButton::clicked, handleCustomTemp);

    //widget for custom temp
    layout->addWidget(customTemp, 1,2,1,1);
    layout->addWidget(addCustomTemp, 1,3,1,1);
    layout->addWidget(submitButton, 1,4,1,1);
   // 

The issue I currently have is that once the submitButton button is clicked, the program crashes (or maybe just closes I'm not sure). I tried setting the default to false but that did not work.

Adam Gong
  • 41
  • 5
  • 3
    Is `addCustomTemp` still in scope when the lambda `handleCustomTemp` is invoked? If not then `addCustomTemp` needs to be captured by value otherwise the expression `addCustomTemp->text()` in the lambda will refer to a dangling reference. – G.M. Jun 06 '23 at 06:04
  • Does this answer your question? [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Abderrahmene Rayene Mihoub Jun 06 '23 at 07:29

1 Answers1

0

Here

auto handleCustomTemp = [&]() {
      QString tempVal = addCustomTemp->text();
      tempValDouble = tempVal.toDouble();
      qDebug() << "Custom temp:" << tempValDouble;
  };

addCustomTemp local variable is captured by reference. When called later, it is a dangling reference to the long gone local variable.

Capture explicitly, on this case by value, to avoid this kind of mistakes:

auto handleCustomTemp = [addCustomTemp]() {

Or, if you want to be lazy, at least capture as value implicitly:

auto handleCustomTemp = [=]() {
hyde
  • 60,639
  • 21
  • 115
  • 176