struct: constructor/destructor for fixing C2280 error: attempting to reference a deleted function
Solved
General and Desktop
-
wrote on 8 Jul 2020, 17:00 last edited by
Hello!
I got a C2280 error with next code:struct my_struct{ QTcpSocket sock; }; std::vector<my_struct> my_vector; int main(int argc, char *argv[]){ QCoreApplication a(argc, argv); for(int i = 0; i < 10; i++){ my_struct mtca; my_vector.push_back(mtca); } return a.exec(); }
There is an error with the copying objects to the vector.
I got the same error when using a QMutex in this struct.
As I understood, I need to use pointers.struct my_struct{ QTcpSocket *sock = nullptr; my_struct(){ sock = new QTcpSocket; } }; std::vector<my_struct> my_vector; int main(int argc, char *argv[]){ QCoreApplication a(argc, argv); for(int i = 0; i < 10; i++){ my_struct mtca; my_vector.push_back(mtca); } return a.exec(); }
How to work correctly with a dynamic creation and destroying objects in the structs?
Thank you! -
QObjects can not be copied. Use a pointer (or smart pointer) in your struct.
-
Hi
Anything that inherits QObject cannot be copied as that would make signal and slot go amok.So easy fix is to use pointers to such members
struct my_struct { QTcpSocket *sock; my_struct() : sock(new QTcpSocket ) {} // let constructor allocate it. ~my_struct() { sock->deleteLater(); // remember to deallocate it } };
oh Mr Ehrlicher beat me to it :)
1/3