0

In the Infinite Skills "Advanced C++ Programming Training Video", in a section about function templates, the presenter said that while passing the arguments to such function, we need to pass them by references and not by values as it might result in compiler giving us a "hard time". I have no idea about what this could be. The function calculates the maximum value of the two arguments and returns the same. The two functions are as follows:

// The function given in the tutorial
T maxVal(T &a1, T &a2)
{
    if(a1<a2)
        return a1;
    else
        return a2;
}

// My function
T maxVal(T a1, T a2)
{
    if(a1<a2)
        return a1;
    else
        return a2;
}

The problem is that both of the seem to work fine. Could you please help me by telling what are possible "hard times" that I can get ?

4

1 回答 1

0

第一个采用非 const 引用将不支持: max(1, 2); 第二个按值取参数将复制参数: max(huge_object_a, huge_object_b); // 不过,编译器可能会优化。

std::max是:

template <class T> const T& max(const T& a, const T& b);
于 2013-08-11T12:20:42.607 回答