Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return const reference to local variable correctly

Tags:

c++

qt

Additionally to the answers 1, 2, 3 and GotW88, assume the following methods

QString createString()
{
    return QString("foobar");
}

const QString& getString()
{
    return createString();
}

This will yield the famous "warning C4172: returning address of local variable or temporary" with VS2013.

Now if i changed the second method to

const QString& getString()
{
    const QString& binder = createString();
    return binder;
}

Which does not report an error anymore. Is this a safe way to fix the warning without changing the signature of the API? Why does this work?

like image 792
x29a Avatar asked Sep 07 '26 04:09

x29a


1 Answers

It doesn't work. That way you simply suppress the warning by making the situation harder to analyze. The behavior is still undefined.

like image 84
AnT Avatar answered Sep 09 '26 19:09

AnT