I'm looking at the Qt example "Table Model Example"
In that example, the createConnection() method in connection.h contains the following code:
static bool createConnection()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":memory:");
if (!db.open()) {...
I duplicated this example in my code. I don't understand 2 things about it.
The local variable db is destroyed at the end of the createConnection() function (see RAII). Since my database doesn't need to be initialized and I'm not using the "db" variable, I can't see why I need this code. However, if I remove it, I my program fails to read from my existing database. I would expect the destruction of the db would close the database and make it unavailable. However, since I don't touch the db variable, why does it need to be created then destroyed before I can access the database? Since I don't use the db variable anywhere and it is destroyed before my code is called, I fail to see why I need to call the createConnection() function at all. On the other hand, I don't see how to open the database and cause the variable destruction to have exception safe RAII code.
I never get db.open() to fail. If I don't have the database, it creates it then opens a blank one. If I do have the database, it opens it. I have a database and if for any reason it fails to open, I don't want it created, I want an error since something is seriously wrong. Opening a blank database can only be trouble for me. How do I handle this case?
I'm new to Qt, but very experienced in C++. This code makes little sense to me. I would expect the db variable's lifetime be the lifetime of the open database. As coded in the example, I fail to see how this code isn't having a resource leak. From what I can tell, initializing db opens some sort of global resource and keeps it open even after the db variable is destroyed causing a leak.
This is very confusing.
Thx.
H Os Tile
Aucun commentaire:
Enregistrer un commentaire