Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does `::operator new` do?

I am looking through some example code of overloading new/delete

and there I have the following

// manage memory for instances
void * roun_class:: operator new(std::size_t s)
{
    void * result(::operator new(s));
    return result;    
}

This is the first time , I am looking at ::operator. And I cannot find anything about it in Google/SO. So , can someone please explain why we have :: and no class infront of it. What is so special about this ::operator ?? ,

FYI, I have already looked at the following what does ::operator() do? Does not really answer my question though

like image 389
thassan Avatar asked Sep 29 '26 02:09

thassan


2 Answers

A leading :: generally indicates the global namespace (ie, no namespace), so I'm guessing ::operator new is necessary to indicate that we're talking about the built-in new, and not recursively calling the class's new.

like image 151
alecbz Avatar answered Oct 01 '26 14:10

alecbz


::operator new(std::size_t) is the new(std::size_t) operator in the global namespace (ie: one of the default memory allocation functions).

It's called ::operator new here because if it weren't, this operator new would simply be calling itself over again, which would lead to a stack overflow.

like image 23
cHao Avatar answered Oct 01 '26 15:10

cHao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!