On Monday, 22 June 2015 11:14:39 UTC+3, Paul wrote:
> Is it ok to return const references to local variables. For example,
> the code below appears to run fine on my machine but it does give a
> warning.
No. It is undefined behavior.
It is good that it gives a warning because defective function
whose behavior is undefined but that appears to run fine in simple
test will (by Murphy's laws) blow everything up in most embarrassing
and damaging for your reputation situation.
> Thanks.
Also there is other defect and it is inefficient.
> /** 2 * Return the maximum item in array a.
3 * Assumes a.size( ) > 0.
4 * Comparable objects must provide operator< and operator=
5 */
Comparable must be of type that is or converts implicitly
to 'int' (for example provides non-explicit 'operator int()') or ...
> template <typename Comparable>
> const Comparable & findMax( const std::vector<Comparable> & a ) {
> int maxIndex = 0;
> int max = a[0];
... or above line is programming error.
> for( int i = 1; i < a.size( ); ++i )
> max = std::max(max, a[i]);
>
> return max;
> }
>
> int main()
> {std::vector<int> x = {23, 45, 67, 98, 3450, -10};
> std::cout << std::endl << findMax(x) << std::endl;
> }
Inefficiency: your algorithm makes pointless copies of the
elements of vector.
There is 'std::max_element' that is more generic (works with
any iteratable sequence) and significantly outperforms
your algorithm on case the elements are cheap to compare
but expensive to copy. I trust I already wrote that in other
quite similar thread that you started.