Using std::less with nullptr

前端 未结 2 1871
伪装坚强ぢ
伪装坚强ぢ 2021-01-01 23:29

Does the assertion in the following code snippet always hold?

std::less lessPtr;
Object * o = new Object();
assert(lessPtr (o, nullptr) == fa         


        
      
      
      
2条回答
  •  星月不相逢
    2021-01-01 23:55

    No, the ordering of a null pointer relative to any non-null pointer is unspecified.

    The result of the comparision operators is unspecified if the operands "point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null".

    std::less and friends extend this to specify that there's a total order, but don't specify where null pointers occur in that order. So it's guaranteed that null will consistently be either greater than, or less than, any given non-null pointer. But it's not specified to be either less than, or greater than, all non-null pointers.

提交回复
热议问题