3

why is std::less<int>() a function object as used in

std::sort(vec.begin(),vec.end(),std::less<int>());

but std::less<int> is a type and operator is function call, there is no object been created, or memory address we can reference

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
Jack Chin
  • 525
  • 4
  • 12

2 Answers2

8

std::less<int>() is a constructor call. It creates a new std::less<int> object which, yes, has overloaded operator().

Joker_vD
  • 3,715
  • 1
  • 28
  • 42
  • 1
    Nitpick: `T()` is *value-initialization* of a temporary of type `T`. It does create an object, but the behavior might be different than that of the default constructor. – David Rodríguez - dribeas Jul 08 '14 at 12:03
  • @DavidRodríguez-dribeas Value-initialization may omit the call to the default constructor? Oh for the... – Joker_vD Jul 08 '14 at 13:32
  • On the contrary, value initialization offers stricter guarantees. For example the default ctor of a POD is a noop, but value initialization guarantees all members will be set to zero. – David Rodríguez - dribeas Jul 08 '14 at 14:01
3

std::less<int>() does actually create a temporary instance of std::less that has a memory address (even though it is empty and therefore won't occupy any real memory with any sane compiler). sort keeps this instance around and uses its overloaded operator () to perform comparisons.

std::less<int>()(a, b) would directly perform a comparison between two integers in case the use of both object creation syntax and operator() calls is what confused you.

Alexander Gessler
  • 45,603
  • 7
  • 82
  • 122
  • Nitpick: all objects do occupy some space, it is up to the compiler to decide how much, but it must occupy at least 1 byte in any *conforming*, *sane* or not, compiler. – David Rodríguez - dribeas Jul 08 '14 at 12:05
  • @DavidRodríguez-dribeas Strictly speaking, the compiler could allocate no memory for the object, but only if such an action can be detected with the use of UB. – Joker_vD Jul 08 '14 at 13:35