0

i'm learning stl, there is member function in new_allocator class:

  pointer
  allocate(size_type __n, const void* = 0)
  {
if (__n > this->max_size())
  std::__throw_bad_alloc();

return static_cast<_Tp*>(::operator new(__n * sizeof(_Tp)));
  }

there is no name but default value in second paramter,what's is the meaning like doing this?

lan muming
  • 13
  • 4

1 Answers1

1

The parameter name isn’t required if the function doesn’t need to reference the parameter, and leaving it unnamed avoids a compiler warning about an unused parameter.

The default value allows callers to call the function with a single argument, and the compiler will treat it as if they called it with two arguments, with the second argument being specified as the default value.

As for why the programmer might include a second, unnamed, unused argument rather than just having the function take a single argument — one reason might be that the user wants the function to fit a particular interface that takes two arguments (eg for inheritance or SFINAE purposes)… or maybe they are planning to change the function to actually use the second argument later, but haven’t got around to doing it yet.

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234
  • 2
    "*the user wants the function to fit a particular interface that takes two arguments*" - Yes, the [Allocator](https://en.cppreference.com/w/cpp/named_req/Allocator) interface. See [`std::allocator::allocate()`](https://en.cppreference.com/w/cpp/memory/allocator/allocate): "*The pointer `hint` may be used to provide locality of reference: the allocator, **if supported by the implementation**, will attempt to allocate the new memory block as close as possible to `hint`.*" In this case, the implementation in question doesn't support this feature, but it still has to follow the interface. – Remy Lebeau May 30 '22 at 03:02