`C++ Core Guidelines` - would `void addWidget(QWidget *w)`, have been better if returned w?
-
https://doc.qt.io/qt-6/qlayout.html#addItem
Hi
Imagining
void addWidget(QWidget *w)
whereQWidget &addWidget(QWidget *w)
then the Qt framework would beC++ Core Guidelines
complaint.
(or maybeQWidget *addWidget(QWidget *w)
)This will enable us to assume ownership
std::moved
though we still in Parent memory management.Or maybe it could even be
QWidget &addWidget(QWidget &&w)
for example:
https://doc.qt.io/qt-6/qtwidgets-tools-echoplugin-example.htmlcould become
void EchoWindow::createGUI() { lineEdit_local = QLineEdit; ... ... ... layout = QGridLayout(); //Later will be moved to the window itself.. layout->addWidget(std::move( QLabel(tr("Message:")) ), 0, 0); lineEdit = layout->addWidget(std::move(lineEdit_local), 0, 1); connect(lineEdit, &QLineEdit::editingFinished, this, &EchoWindow::sendEcho); ... ... ...
-
Hi, welcome to the forum.
Qt's ownership model was created looong before C++ added move semantics and smart pointers. It has its own way of handling it via the parent child mechanism and it works fine. There's absolutely no need to mix those two models just because the standard added it.
Apart from that QObjects are non-copyable and non-movable by design, so things like
lineEdit_local = QLineEdit
orstd::move(QLabel...
are out of the question. The library is just not designed around references, so changing it would pretty much mean rewriting entire Qt into something else.Besides, C++ Core Guidelines are just that, guidelines for designing code. Qt was designed waaaaay before they were and it follows quite a different philosophy. It's wort remembering that Qt's fundamental design and rules were created before even C++98. At that point in time there were different approaches emerging and Qt and std:: went different ways. It doesn't automatically mean one or the other is better or worse. They both accomplish roughly the same idea, just in different ways. Trying to combine them is not a good idea though.
And just to clarify - even if you'd make QObject movable the method you want to write would be
QWidget& addWidget(QWidget&& w)
and invocation would beaddWidget(QLabel(tr("Message:")));
. Objects created as in-line parametrs are already r-values, so move is not necessary in that case. The way you wrote it wouldn't compile. You can't use move to turn r-value into a pointer.