I have a class which is absfilehandler which has a QFILE pointer like this..
QString absfilename;
QFile * absfilepointer;
I have a opening method.
bool AbsFileHandler::OpenAbsFile()
{
QFile readfile(absfilename);
absfilepointer = (&readfile);
if (!(*absfilepointer).exists())
{
qDebug() << "The file" << (*absfilepointer).fileName() << "does not exist.";
return false;
}
else if (!(*absfilepointer).open((QIODevice::ReadOnly) | (QIODevice::Text)))
{
qDebug() << "Could not open" << (*absfilepointer).fileName() << "for reading.";
return false;
}
else
{
qDebug() << "File ready to read";
return true;
}
}
I call the method in the another class with a object of the same class like this myAbsFileHandler.OpenAbsFile()
if it returns true then we execute this
QTextStream readabsstream((myAbsFileHandler.absfilepointer));
But this statement gives critical exception and comes out of execution. Any idea why this is happening? Thanks.
I suggest not using raw pointers when there is no need to, why do you need to save a
QFile*? I guess you want to create a stream withQTextStream(QIODevice *device), then you can simply pass a pointer to your file if the method needs one.The problem you have is you create a pointer to a local scoped
QFile readfile, since it's created on the stack it will be destroyed at the end of yourAbsFileHandler::OpenAbsFile()method. so the pointer becomes invalid after the method returns!So the solution is just save a
QFile(not a pointer) or create theQFileon the heap withnew QFileto keep the object alive, but that is not a good idea if you have to manage the memory yourself and delete it later.