Why does Release/Debug have a different result for std::min?

前端 未结 3 1326
一整个雨季
一整个雨季 2020-12-16 09:10

Here is the test program:

void testFunc()
{
    double maxValue = DBL_MAX;
    double slope = std::numeric_limits::quiet_NaN();

    std::cout          


        
3条回答
  •  醉酒成梦
    2020-12-16 09:48

    Got it:

    Here is the implementation used by VS in Debug mode (with _Pred being DEBUG_LT, LT for Lower Than):

    template inline
        _CONST_FUN bool _Debug_lt_pred(_Pr _Pred,
            _Ty1&& _Left, _Ty2&& _Right,
            _Dbfile_t _File, _Dbline_t _Line)
        {   // test if _Pred(_Left, _Right) and _Pred is strict weak ordering
        return (!_Pred(_Left, _Right)
            ? false
            : _Pred(_Right, _Left)
                ? (_DEBUG_ERROR2("invalid comparator", _File, _Line), true)
                : true);
        }
    

    Which is equivalent to (more readable):

        if (!_Pred(_Left, _Right))
        {
            return false;
        }
        else
        {
            if ( _Pred(_Right, _Left) )
            {
                assert( false );
                return true;
            }
            else
            {
                return true;
            }
        }
    

    Which, again is equivalent to (!_Pred(_Left, _Right)). Transcripted as a macro, it becomes #define _DEBUG_LT(x, y) !((y) < (x)) (i.e: NOT right < left).

    Release implementation is actually a macro #define _DEBUG_LT(x, y) ((x) < (y)) (i.e: left < right).

    So Debug (!(y and Release (x implementations are definitely not the same and they do behave differently if one parameter is a NaN...! Don't ask why they did that....

提交回复
热议问题