简体   繁体   中英

how compiler identifies the type when overloading new operator in C++

I overloaded new operator. But I wonder how compiler identified the type when I called the global new operator inside overloaded new operator.

#include<iostream>

class Samp{
    public:
    Samp(){
        std::cout<<"constructor\n";
    }
    void* operator new(size_t sz){
        std::cout<<"operator overloading new\n";
        return ::operator new(sz);
    }
};

int main(){
    Samp* a=new Samp;

    return 0;
}

Here, the output is -

operator overloading new   
constructor           

When I overload, inside the new overloaded function, I provided only the size_t sz (which is just size), by taking that alone as argument how compiler identified this is of type Samp and called the corresponding constructor??

In the expression

new Samp;

the C++ compiler sees that it's trying to construct something of type Samp . From there, it can then ask - which operator new function should I be using to do this? There's always the global operator new it can pick from, but since the compiler knows it's building a Samp it can also ask "does Samp overload operator new ?" That then tells it to look inside Samp , and that's how it finds your overload.

Notice that, in this discussion, I've been talking about which operator new function to call. There's a subtle distinction here between "the new operator" and "the function operator new ." Specifically:

  • operator new is a function that provides the raw bytes of storage that's needed to store an object.
  • The new operator first calls operator new to get space, then calls the constructor for the object in the space returned this way.

When you're overloading operator new , you're saying "when I need to get space for an object, please use this function to get the bytes where I'd like you to put that object." That's separate from actually creating the object in those bytes. That's handled by the expression new Samp , which then takes those bytes and calls the constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM