Paul <
peps...@gmail.com> writes:
> The below is quoted from a C++ text. However, I have been unable to
> implement the idea. Whenever I try, I get the warning for a function
> returning a reference to a local variable and a runtime error. Does
> anyone see how to make the idea work?
>
> For example, a typical simple-as-possible findMax implementation would
> be something like
>
> int findMax(std::vector<int> vec)
> {
> if(vec.empty())
> throw std::runtime_error("Empty vector");
>
> int max = vec[0];
> for(int i = 1; i < vec.size(); ++i)
> if(vec[i] > max)
> max = vec[i];
>
>
> return max;
>
> }
>
> If we change the signature to return a reference, I understand
> perfectly that we get an error because we're returning a reference to
> the local variable max. But if we don't do that, what does the author
> have in mind?
I suspect the author is thinking of something like
const int& findMax(const std::vector<int>& vec)
{
if(vec.empty())
throw std::runtime_error("Empty vector");
int maxi = 0;
for(int i = 1; i < vec.size(); ++i)
if(vec[i] > vec[maxi])
maxi = i;
return vec[maxi];
}
<snip>
> However, notice that if the vector stores large objects, then the
> result is that x will be a copy of the largest value in arr. If we
> need a copy for some reason, that is fine; however, in many instances,
> we only need the value and will not make any changes to x. In such a
> case, it would be more efficient to declare that x is another name for
> the largest value in arr, and hence we would declare x to be a
> reference (auto will deduce constness; if auto is not used, then
> typically a non-modifiable reference is explicitly stated with const):
> auto & x = findMax( arr );
> Normally,this means that findMax would also specify a return type that
> indicates a reference variable.
--
Ben.