How is QSqlTableModel ok?
-
So here is my issue: the documentation for
QSqlDatabase
has a pretty big warning:Warning: It is highly recommended that you do not keep a copy of the QSqlDatabase around as a member of a class, as this will prevent the instance from being correctly cleaned up on shutdown. If you need to access an existing QSqlDatabase, it should be accessed with database(). If you chose to have a QSqlDatabase member variable, this needs to be deleted before the QCoreApplication instance is deleted, otherwise it may lead to undefined behavior.
QSqlTableModel
explicitly goes against that warning: stores the db and never takes care of deleting it safely.How is it ok? Am I missing some magic somewhere?
-
Hi,
On the deleting part, the model shall be deleted before the QCoreApplication and thus its private part as well and thus the db object.
As for why they did it like that, it's rather a question for the original developer.
-
@SGaist said in How is QSqlTableModel ok?:
the model shall be deleted before the QCoreApplication and thus its private part as well and thus the db object.
Not necessarily... for example
#include <QApplication> #include <QTableView> #include <QSqlTableModel> #include <memory> int main(int argc, char *argv[]) { std::unique_ptr<QSqlTableModel> model; QApplication a(argc, argv); QSqlDatabase db = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE")); db.setDatabaseName(QStringLiteral("/path/to/mydb.sqlite")); Q_ASSUME(db.open()); model = std::make_unique<QSqlTableModel>(); model->setTable(QStringLiteral("MyTable")); Q_ASSUME(model->select()); QTableView tableView; tableView.setModel(model.get()); tableView.show(); return a.exec(); }
Now we can agree that, in practice, it seldom happens but I still don't understand if the design choice opens up the problem without safeguards or warnings or if I'm just missing something that makes it ok.