In line 12, you're taking the address of the QSqlDatabase object returned by addDatabase()
. That object is temporary and destroyed right away after the end of the statement (after line 12). So you end up with a dangling pointer, i.e. a pointer to an already deleted object.
Dereferencing a dangling pointer is undefined behavior. In practice, it usually crashes.
In line 14, a new QSqlDatabase object is created on the heap, creating a copy of the temporary QSqlDatabase object returned from addDatabase(). The copy constructor QSqlDatabase(const QSqlDatabase&) is called here. The temporary object is destroyed, but the copy on the heap remains. Note that you have to delete db
later, otherwise you end up with a memory and resource leak (open DB connection).
Why do you use a pointer here at all? Especially as a beginner, all it will result in is crashes and leaks, as this example demonstrates ;)