Where does the "size" come from?

I know that there should be a delete operator with which I am not interested somewhere. I'm just curious, wow, it worked. Where is the argument "size" coming from?

#include<iostream> #include<string> class Base { public: Base() { } void *operator new( unsigned int size, std::string str ) { std::cout << "Logging an allocation of "; std::cout << size; std::cout << " bytes for new object '"; std::cout << str; std::cout << "'"; std::cout << std::endl; return malloc( size ); } private: int var1; double var2; }; int main(int argc, char** argv){ Base* b = new ("Base instance 1") Base; } 

Here is the result:

Record of allocation of 16 bytes for a new object "Basic instance 1"

+6
source share
2 answers

It is provided by the compiler at compile time. When the compiler sees:

 new ("Base instance 1") Base; 

he will add a call:

 Base::operator new(sizeof(Base), "Base instance 1"); 

EDIT: The compiler, of course, will add a call to Base::Base()

+12
source

on a 32-bit architecture, int 4 bytes, double is 8, but double will be aligned with an 8-byte boundary, so size = 4 + 4 (empty space) + 8 = 16

0
source

Source: https://habr.com/ru/post/895737/


All Articles