3
\$\begingroup\$

I have the following Qt class:
mainwindow.h

class MainWindow : public QWidget {
Q_OBJECT
QPushButton* m_button;
public:
    explicit MainWindow();
};

mainwindow.cpp

MainWindow::MainWindow() {
    auto main_layout = new QHBoxLayout;
    m_button = new QPushButton("Press me");
    main_layout->addWidget(m_button);
    setLayout(main_layout);
    connect(m_button, &QPushButton::pressed, [this] {
        m_button->setText("Presse me again");
    });
}

It features a button which once pressed will change its text to "Press me again". I use a lambda function and I am capturing by copy this to access the button inside the lambda.

As the QPushButton is allocated on the heap, I think that making it a class member is an unnecessary step. My question: Are there any drawbacks if I instead use it as a local pointer which I would capture by copy in the connect lambda ? It would look like this:

mainwindow.h

class MainWindow : public QWidget {
Q_OBJECT
public:
    explicit MainWindow();
};

mainwindow.cpp

MainWindow::MainWindow() {
    auto main_layout = new QHBoxLayout;
    auto button = new QPushButton("Press me");
    main_layout->addWidget(button);
    setLayout(main_layout);
    connect(button, &QPushButton::pressed, [button] { // I am copying the button's address here
        button->setText("Presse me again");
    });
}

One thing to note: Qt manages the destruction of all Qt classes automatically, so no need to call the button's destructor later if I understood correctly this conversation.

\$\endgroup\$

closed as off-topic by Toby Speight, vnp, Zeta, Dannnno, t3chb0t Jan 17 at 10:02

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Lacks concrete context: Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site." – Toby Speight, vnp, Zeta, Dannnno, t3chb0t
If this question can be reworded to fit the rules in the help center, please edit the question.