简体   繁体   中英

Does the embedded “new” in the following code cause a memory leak?

I don't believe so, I think the memory is deleted when the function terminates, but I want to check with the community.

void MainWindow::editCopy   (void)
{
    QWidget *pqwgtFocus = QApplication::focusWidget();

    if (pqwgtFocus != 0)
    {
        QApplication::postEvent (   pqwgtFocus,
                                    new QKeyEvent   (   QEvent::KeyPress,
                                                        Qt::Key_C,
                                                        Qt::ControlModifier
                                                    )
                                );

        QApplication::postEvent (   pqwgtFocus,
                                    new QKeyEvent   (   QEvent::KeyRelease,
                                                        Qt::Key_C,
                                                        Qt::ControlModifier
                                                    )
                                );
    }

    return;
}

Yes the application will take ownership and it's perfectly safe.

The event must be allocated on the heap since the post event queue will take ownership of the event and delete it once it has been posted. It is not safe to access the event after it has been posted.

https://doc.qt.io/qt-5/qcoreapplication.html#postEvent

There is no memory leak here. QApplication::postEvent takes ownership of the pointer and will call delete on it when done:

The event must be allocated on the heap since the post event queue will take ownership of the event and delete it once it has been posted. It is not safe to access the event after it has been posted.


Do note that this is really poor interface. You have to explicitly check the documentation to make sure you are using the function correctly. Had it instead accepted a QScopedPointer then you would know just by looking at the function signature that postEvent was taking ownership of the pointer.

postEvent takes ovnership of the event and delete s it when it's done with it. No leak.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM