Why max (max(a,b), c) is error

前端 未结 1 1732
伪装坚强ぢ
伪装坚强ぢ 2020-12-19 20:13

Reference: code snippet from C++ Template: The Complete Guide

// maximum of two values of any type (call-by-reference) 
template  
inline T         


        
相关标签:
1条回答
  • 2020-12-19 20:41

    The problem is that the C-string flavor of max returns by value, not so much that it takes its arguments by value. The generic 3-way max function is declared to return a reference but the C-string max returns a value, which would then result in returning a reference to a temporary that will be dead before you can access it.

    Update: The new code you added is not equivalent to your original problem. This would:

    const int*& fReturnValue(const int *i)
    {
        return i;
    }
    

    Note that fReturnValue returns a reference to the local variable i, whose lifetime ends by the time the function returns. So the function returns a reference to an invalid object. Try to compile your code with that change, you should get a warning from pretty much every compiler.

    0 讨论(0)
提交回复
热议问题