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;
}