Syntax for using std::greater when calling std::sort in C++

Why are there parentheses after std::greater there? Are we creating a new std::greater object here?

That’s correct. The expression std::greater<int>() corresponds to creating an object of type std::greater<int>.

In that case, why don’t we need the new keyword here?

We don’t need the new keyword because the object is being created on the stack, rather than on the heap. Only objects created dynamically need to be on the heap. The difference is clearly explained here.

Basically, at compile time, the compiler already knows how much memory to allocate for the object, as well as when it should be destroyed (which is when the std::sort function goes out of scope). new should be used whenever

  • this information is not available — a simple example is when you want to create an array of objects, but you don’t know how many objects, until the program actually runs; and/or
  • you want objects to have persistent storage duration, i.e. you want the object to outlast the lifetime of the scope where it was created.

Leave a Comment