PDA

View Full Version : Returning const &



frenk_castle
24th November 2009, 00:19
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.



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;
}


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
}


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&?



QStringList list;
QString name("somefile");

list = readFile(name);


or



const QStringList& WODAL::loadClientList()
{
return readFile(m_clientListFileName); //m_clientList is of QString type and was previously initialized
}


Thanks in advace.

Coises
24th November 2009, 05:34
When returning a reference, as a quick check on your logic, you can think, “What would happen if it were a pointer?” Could you return a pointer to result? Of course not, because once the member function ends, its local variables, including result, won’t exist anymore.

Fortunately, there is no need to get into this trap with QString and QStringList, because they are implicitly shared (http://doc.trolltech.com/4.5/shared.html). You can pass implicitly shared classes as arguments and return them from functions as values (that is, not using pointers or references) without incurring the overhead of copying data; so there is usually no advantage to using const ...& with these classes.

frenk_castle
24th November 2009, 07:01
Implicit sharing was one of the reasons I asked the question. I was 90% sure that returning const& is bad because that variable is on stack. One you return from function that stack memory is marked as free and something will overwrite the variable whose reference I returned. Thanks for the quick reply.