Say I have a function that creates a QIODevice (e.g. a QFile), then returns a pointer to a QDataStream constructed from the QIODevice. What is the best way to deal with the memory allocation here? Clearly the QIODevice must be heap allocated to stay available to the QDataStream upon function termination, however the destruction of a QDataStream does not destroy or close the device. Is there a standard way of dealing with this seemingly common problem?
Ideally I want a function that returns an object (not a pointer to an object) that behaves like a QDataStream but upon destruction closes the device. Effectively a standard library input stream.
Example code:
QDataStream* getStream(const QString& filename) {
QFile* file = new QFile(filename); // needs to be explicitly deleted later
file->open(QIODevice::ReadOnly);
QDataStream* out = new QDataStream(&file); // same here
return out;
}
std::unique_ptris another option depending on your needs; here’s a reference for the former if you need it.Edit: Qt also has the facility for this with its QSharedPointer class, where you can also supply a deleter as a constructor argument. Other pointer wrapper options are given there. Thanks @RA. for the correction.