How to use QScopedPointer in lambda function?

Viewed 156

I created a widget object using QScopedPointer utility and used it in a lambda connect function. As a result, it generated a compile time error.

 QScopedPointer<QMessageBox> errBox(new QMessageBox());
    errBox->setText("some text");
    QObject::connect(errBox,&QMessageBox::buttonClicked,this,[=](QAbstractButton *button){
        qInfo()<<"clicked button"<<button->text();
    });

However when I replaced QScopedPointer with normal initialization it worked perfectly.

QMessageBox *errBox = new QMessageBox();
errBox->setText("some text");
QObject::connect(errBox,&QMessageBox::buttonClicked,this,[=](QAbstractButton *button){
    qInfo()<<"clicked button"<<button->text();
});

I explored Qt Docs and found that:

The code the compiler generates for QScopedPointer is the same as when writing it manually. Code that makes use of delete are candidates for QScopedPointer usage (and if not, possibly another type of smart pointer such as QSharedPointer). QScopedPointer intentionally has no copy constructor or assignment operator, such that ownership and lifetime is clearly communicated.

I want to know the reason for compilation error. Is there some other way to use QScopedPointer in lambda? What am I missing here?

1 Answers

The problem is not in the lambda. The problem is that, like std::unique_ptr, QScopedPointer does not cast automatically to a pointer, so your compiler probably complains about not finding a QObject::connect taking a QScopedPointer. Try:

QObject::connect(errBox.get(), ...
Related