QList uses move constructor?
-
Hi, I am using
Qt6.3
and I am trying to store an object in aQList
. My object provides the default constructor, copy constructor, copy assignment operator and destructor but I have deleted the move constructor and move assignment operator.class Base { public: Base(Base&& other) = delete; // deleted move constructor Base& operator=(Base&& other) = delete; // deleted move assignment operator Base(); // default constructor Base(const Base& other); // copy constructor Base& operator=(const Base& other); // copy assignment operator ~Base(); // destructor int value{0}; }; QDataStream& operator<<(QDataStream& out, const Base& obj); QDataStream& operator>>(QDataStream& in, Base& obj); Q_DECLARE_METATYPE(Base)
In my cpp file:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); qRegisterMetaType<Base>(); Base base; QList<Base> baseList; baseList << base; // produces error C2280 }
When I try to store my object in a
QList
I get an error:C2280 'Base::Base(Base &&)': attempting to reference a deleted function
It is trying to access the move constructor when I am trying to store
base
in mybaseList
, which is deleted and so I am getting the error. When I comment out the deleted move constructor then it works.According to Qt's documentation from Container Classes webpage:
The values stored in the various containers can be of any assignable data type. To qualify, a type must provide a copy constructor, and an assignment operator. For some operations a default constructor is also required.
And from the
QList
webpage:QList's value type must be an assignable data type.
In
Qt6
QList
has the same implementation asQVector
inQt5
:Prior to Qt 6, QVector and QList were separate classes. In Qt 6, they are unified: Qt 5 QList implementation is gone and both classes use updated QVector implementation instead. QList is the class with the actual implementation and QVector is an alias (typedef) to QList.
The
QVector
inQt5
used to use copy constructor to store data. So, why is it trying to access the move constructor in the first place? And is there any way to avoid it without writing an explicit move constructor? -
@CJha it is ?
because I ran into the issue, that QList insisted to use the copy assignment operator, no matter what.
https://bugreports.qt.io/browse/QTBUG-101432
that said,
Your class has a user declared copy constructor, so simply don't declare the move assignment at all, then no implicit move assignment operator will be created and the copy assignment should be selected.
-
@J-Hilk Thanks! Ok, so removing the deleted move constructor and move assignment operator works. I was marking it
delete
because I wanted to avoid implicitly generated move semantics, but now I understand that it won't be generated by itself if I have a copy constructor already.It is still weird that
QList
was giving error for deleted move semantics when it is not using move semantics at all.