I am allocating memory for an object and if a particular statement following the memory allocation fails, I have to delete the memory and also throw an exception.
For example say
QSqlQuery *query = new QSqlQuery(db);
try {
query->prepare(somestmt);
}
catch (...) {
throwException(*query);
}
Here where and how should I delete query if an exception is thrown?
Thanks!
The answer depends on how long you need the query object to stay alive. If you don’t need it outside the try/except block, then it’s probably best to use RAII to delete it as soon as you leave that block. E.g., using boost::scoped_ptr, you could do this:
But from your example, it looks like you want to keep the query object, or a copy of it, around past that block. If it’s ok to just keep a copy of it, then you could do this:
Or this, if you don’t like using boost:
If you need to keep the original query itself, then you probably would need to require the exception object itself to delete it. I.e., do something like this:
Where part of “MyException”‘s contract is that it takes ownership of its argument (i.e., responsibility for deleting it).
Another option would be to use shared pointers. I.e.:
This has the advantage that the query gets deleted when the last shared pointer to it goes away, which makes memory management much easier.