Why does the following code print true instead of false?
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
if (!openDatabase()) return 1;
// false means don't open closed connections.
QSqlDatabase db2 = QSqlDatabase::database("foo", false);
qDebug() << db2.isOpen();
return 0;
}
bool openDatabase()
{
QSqlDatabase db1 = QSqlDatabase::addDatabase("QPSQL", "foo");
db1.setHostName("localhost");
db1.setUserName("user");
db1.setPassword("password");
db1.setDatabaseName("bar");
return db1.open();
}
According to example #2 in the first answer to What is the correct way of QSqlDatabase & QSqlQuery?, the database connection is closed when the QSqlDatabase
object goes out of scope. Thus, when db1
goes out of scope at the end of openDatabase()
, the connection should be closed.
(What actually happens is a bit more subtle. Internally, QSqlDatabase
maintains a reference count of the QSqlDatabase
objects it has returned for a particular connection. The reference count is decremented by ~QSqlDatabase
and, when it reaches 0, the connection is closed. However, this should not change anything. The reference count should be 1 after the first line in openDatabase()
and 0 after the function ends and db1 is destroyed.)
What am I missing?