0

I found the following declaration on StackOverflow to replace the new / delete operator. But i would like to understand this notation How to properly replace global new & delete operators

void * operator new(decltype(sizeof(0)) n) noexcept(false)

Now let's split up: New obviusly needs to return a Pointer. And new is used as an operator. So far so good. It is also clear to me the n must represent the number of bytes to allocate. The unclear part is the argument:

sizeof(0) (on a 32bit machine) evaluates to sizeof(int) = 4 Then I got decltype(4 n)??? What does this mean?

HugoTeixeira
  • 4,674
  • 3
  • 22
  • 32
JuliusCaesar
  • 341
  • 3
  • 14
  • 1
    You misread the parentheses, the `decltype` only encapsulates the `sizeof`, the `n` is just a function parameter name – UnholySheep Aug 22 '18 at 21:53

2 Answers2

1

decltype(sizeof(0)) n does not mean decltype(4 n). In

void * operator new(decltype(sizeof(0)) n) noexcept(false)

the decltype(sizeof(0)) n part means the parameter is named n and it has the type of what sizeof(0) returns. You could replace this with

void * operator new(std::size_t n) noexcept(false)

since sizeof is guaranteed to return a std::size_t per [expr.sizeof]/6 but doing it the first way means you don't need to include <cstddef>

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
1

n needs a type.

The type is deduced by decltype(sizeof(0)).

sizeof(0) evaluates to a value of 4 but its type is std::size_t. It's as if you had used

std::size_t s = sizeof(0);
using type = decltype(s); // Only the type is important here, not the value.
void * operator new(type n) noexcept(false)
R Sahu
  • 204,454
  • 14
  • 159
  • 270