In my app I have I class that handles file IO. I have a protected method that contains the code for reading from a file. Basically every method that reads from a file makes some preparations and that calls this protected method.
{
{
stream.setDevice(&file);
while(!stream.atEnd())
{
result.append(stream.readLine());
}
}
file.close();
return result;
}
QStringList WODAL::readFile(const QString &name)
{
QStringList result;
QFile file(name);
QTextStream stream;
if(file.open(QIODevice::ReadOnly | QIODevice::Text))
{
stream.setDevice(&file);
while(!stream.atEnd())
{
result.append(stream.readLine());
}
}
file.close();
return result;
}
To copy to clipboard, switch view to plain text mode
When I change the return type from QStringList to const QStringList& I get the compiler warning returning of the reference to a local variable, or something like that. Since I have another class which is mostly a property container. It has lot of members that only have setters and getters I wanted to make a getter that is for instance like this
const QString& WOIDL::clientName()
{
return m_clientName; //m_clientName is of QString type
}
const QString& WOIDL::clientName()
{
return m_clientName; //m_clientName is of QString type
}
To copy to clipboard, switch view to plain text mode
For this getter I don't get the warning because m_clientName is not a local variable from some method which will be destroyed upon returning but a class member. My question is: Is it ok to use const QString& and const QStringList& in these cases or not? Its been a while since I read on these topics and I am not sure when is return variable destroyed. For instance will this code be ok if I write it in some method of the WODAL class in case return type is const QStringList&?
list = readFile(name);
QStringList list;
QString name("somefile");
list = readFile(name);
To copy to clipboard, switch view to plain text mode
or
const QStringList& WODAL::loadClientList()
{
return readFile(m_clientListFileName); //m_clientList is of QString type and was previously initialized
}
const QStringList& WODAL::loadClientList()
{
return readFile(m_clientListFileName); //m_clientList is of QString type and was previously initialized
}
To copy to clipboard, switch view to plain text mode
Thanks in advace.
Bookmarks