如何在 lambda 函数中使用 QScopedPointer?
How to use QScopedPointer in lambda function?
我使用 QScopedPointer 实用程序创建了一个小部件对象,并将其用于 lambda 连接函数。结果,它产生了一个编译时错误。
QScopedPointer<QMessageBox> errBox(new QMessageBox());
errBox->setText("some text");
QObject::connect(errBox,&QMessageBox::buttonClicked,this,[=](QAbstractButton *button){
qInfo()<<"clicked button"<<button->text();
});
然而,当我用正常初始化替换 QScopedPointer 时,它工作得很好。
QMessageBox *errBox = new QMessageBox();
errBox->setText("some text");
QObject::connect(errBox,&QMessageBox::buttonClicked,this,[=](QAbstractButton *button){
qInfo()<<"clicked button"<<button->text();
});
我研究了 Qt Docs 并发现:
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.
我想知道编译错误的原因。还有其他方法可以在 lambda 中使用 QScopedPointer 吗?
我在这里错过了什么?
问题不在 lambda 中。问题是,与 std::unique_ptr
一样,QScopedPointer
不会自动转换为指针,因此您的编译器可能会抱怨找不到 QObject::connect
接受 QScopedPointer
。尝试:
QObject::connect(errBox.get(), ...
我使用 QScopedPointer 实用程序创建了一个小部件对象,并将其用于 lambda 连接函数。结果,它产生了一个编译时错误。
QScopedPointer<QMessageBox> errBox(new QMessageBox());
errBox->setText("some text");
QObject::connect(errBox,&QMessageBox::buttonClicked,this,[=](QAbstractButton *button){
qInfo()<<"clicked button"<<button->text();
});
然而,当我用正常初始化替换 QScopedPointer 时,它工作得很好。
QMessageBox *errBox = new QMessageBox();
errBox->setText("some text");
QObject::connect(errBox,&QMessageBox::buttonClicked,this,[=](QAbstractButton *button){
qInfo()<<"clicked button"<<button->text();
});
我研究了 Qt Docs 并发现:
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.
我想知道编译错误的原因。还有其他方法可以在 lambda 中使用 QScopedPointer 吗? 我在这里错过了什么?
问题不在 lambda 中。问题是,与 std::unique_ptr
一样,QScopedPointer
不会自动转换为指针,因此您的编译器可能会抱怨找不到 QObject::connect
接受 QScopedPointer
。尝试:
QObject::connect(errBox.get(), ...