1

I'm overloading the "new" operator in order to keep track of every allocation. I want it to print the size of the allocated memory, as well as the type of the object that is allocated.

I've come up with something like this:

void* operator new(size_t size) {
  std::cout << "Allocating " << size << " bytes.\n";
  return malloc(size);
}

but I have no clue on how to print the type of the object. Thank you for the help!

MSalters
  • 173,980
  • 10
  • 155
  • 350
LucioPhys
  • 161
  • 9
  • 3
    AFAIK you are out of luck. It is the new expression that deals with the type, not the new operator. – NathanOliver Mar 06 '20 at 15:23
  • You can't get type information here. You could try something as discussed in this Q/A https://stackoverflow.com/questions/583003/overloading-new-delete – RamblinRose Mar 06 '20 at 15:24
  • 2
    At that point there is no object yet, so there is nothing you can find the type of. `operator new` is only a memory allocation function. – molbdnilo Mar 06 '20 at 16:10
  • `operator new` is also called by `std::allocator`, so there's no simple solution anyway. That could be in response to `std::vector::reserve`, in which case you would only be allocating raw bytes. – MSalters Mar 06 '20 at 16:53

1 Answers1

0

There is no type involved at all. You specify nowhere any type - what you do is just memory allocation in bytes. So, the type is always an array of size bytes.

Dr. Andrey Belkin
  • 795
  • 1
  • 9
  • 28