PDA

View Full Version : How to return a QFile ?



oldFox64
7th February 2014, 07:54
Sry for the dumb question, but I'm not very experienced with C++ and I don't manage find the appropriate return type of the following function:


?? MyClass::selectFile(){
const QString fileName = QFileDialog::getOpenFileName(this,
tr("Select file"), qgetenv("HOMEPATH")+"\\Desktop", tr("File(*.hex)"));

if(fileName==NULL)
return NULL;

QFile file(fileName);

return ??;

}

nDorian
7th February 2014, 08:55
Helo! You can't return QFile object, because it don't have public copy constructor. It is possoble to return reference or pointer to QFile object but in these case it must be a member of your class (object created in function will be destroyed at the end of function class member not).

stampede
7th February 2014, 09:07
Why not


QString MyClass::selectFile() {
return QFileDialog::getOpenFileName(this, tr("Select file"), qgetenv("HOMEPATH")+"\\Desktop", tr("File(*.hex)"));
}

?

oldFox64
7th February 2014, 09:07
Didn't know that, thank you.

So to return a QFile pointer, how it should be?

nDorian
7th February 2014, 09:29
class MyClass
{
public:
MyClass();


QFile *selectFile();

private:
QFile *myFile;
};

MyClass::MyClass()
{
}

QFile *MyClass::selectFile()
{
const QString fileName = "abc";

if(fileName==NULL)
return NULL;

myFile = new QFile(fileName);

return myFile;
}

stampede
7th February 2014, 10:04
Keep in mind that this solution may lead to memory leak:


QFile *MyClass::selectFile();

//...

QFile * file = selectFile();
if (file) {
doSomethingWithFile(file);
delete file;
}

If "dosomethingWithFile()" throws, control will never reach "delete file" and the resource will leak.
So I don't really understand why you won't use a QString object:


QStrign MyClass::selectFile();

//...

QString filePath = selectFile();
if (filePath.isEmpty() == false) {
QFile file(filePath);
...
}

Or at least use QFile pointer wrapped in smart pointer class, for example QSharedPointer<QFile>.

// edit:
btw. nDorian's code will cause a memory leak if selectFile() is called two or more times in a row without deleting "myFile" pointer in between. I know that this is forum section for "newbies" but this is important, any C++ programmer have to pay attention to such details - I know you are "not very experienced", but the sooner the better :)

oldFox64
7th February 2014, 11:37
I wanted to use QFile object because I thought is more understandable and "natural". But yes, you're right, I'm going to use a QString better.

anda_skoa
7th February 2014, 15:02
QFile is the class that does data I/O.
If you only need a reference to the file use either QString or QFileInfo.

If you need the file, e.g. when you function does more than just create the instance, then return a smart pointer



QSharedPointer<QFile> MyClass:getFile()
{
// ....

QSharedPointer<QFile> file(new QFile(filename);
file->open(...); // or other tasks with file

return file;
}


Cheers,
_