Can't find error on return-by-constant-reference
Sep 20, 2017 at 5:11pm UTC
Can Someone explain why the first one is correct and the second one is wrong?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
const string &findMax(string *a, int n)
{
int maxIndex = 0;
for (int i=1; i<n; i++)
if (a[maxIndex] < a[i])
maxIndex = i;
return a[maxIndex];
}
const string &findMaxWrong(string *a, int n)
{
string maxValue = a[0];
for (int i=1; i<n; i++)
if (maxValue < a[i])
maxValue = a[i];
return maxValue;
}
Sep 20, 2017 at 5:39pm UTC
In the second example, the string
maxValue is a local variable with automatic storage duration. The life time of the object does the extend beyond the duration of the function; the returned reference is invalid (the object to which it refers has already been destroyed.)
If warnings are enabled, the compiler would warn us about it.
http://coliru.stacked-crooked.com/a/ec800ce135dd408a
http://rextester.com/JVK34249
Ideally, make the first function const-correct:
const std::string& findMax( const std::string* a, int n ) ;
Sep 20, 2017 at 5:48pm UTC
thank you! :)
Topic archived. No new replies allowed.