-1

Why following code works? Function max is returning a reference to a copy of vector, which is local variable, but it returns 19 (which is the right answer). I'm using QtCreator 3.5.0

#include <iostream>
#include <vector>

template <class T>
T& max(std::vector<T> array)
{
   T& result = array[0];
   for (size_t i = 1; i < array.size(); i++)
   {
       if (result < array[i])
       {
           result = array[i];
       }
   }
   return result;
}

int main()
{
    std::vector<int> testVector;
    for (size_t i = 0; i < 20; i++)
    {
        testVector.push_back(i);
    }
    std::cout << max(testVector) << std::endl;
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
andrew554
  • 163
  • 1
  • 1
  • 8
  • 3
    You are just lucky - do not depend on it – Ed Heal May 14 '16 at 09:55
  • 2
    If you break the rules, you might go to jail or you might not. Just dont do it – 463035818_is_not_an_ai May 14 '16 at 09:56
  • @hvd yes, sorry, i wanted to say that it wasn't returning a reference to a copy of a vector. – perencia May 14 '16 at 09:57
  • 1
    Aside: `result = array[i];` does not do what you think it does. It assigns to `array[0]`. (Which does not cause immediate problems here, since nothing else reads from `array[0]` until the `return result;`, but will cause problems if you modify the code to take a vector parameter by reference.) –  May 14 '16 at 09:58
  • @hvd I've already found out about this issue using debugger, but it does not explain the main problem – andrew554 May 14 '16 at 10:05
  • @andrew554 Well asking about the behavior of undefined behavior is pretty useless, isn't it? – πάντα ῥεῖ May 14 '16 at 10:07

1 Answers1

2

Returning a reference to a local variable has an undefined behavior. It may work by chance for your usecase, but you shouldn't depend on it. It may (and probably will) break in some horrible way eventually.

Mureinik
  • 297,002
  • 52
  • 306
  • 350