Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the `size` coming from?

I know there should be a delete operator with which I'm not concerned in somewhere. I just wondering, 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:

Logging an allocation of 16 bytes for new object 'Base instance 1'

like image 386
Mike Avatar asked Aug 24 '11 11:08

Mike


1 Answers

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

new ("Base instance 1") Base;

it will add a call to:

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

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

like image 66
Andreas Brinck Avatar answered Nov 14 '22 22:11

Andreas Brinck