Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between new/delete and ::new/::delete?

Tags:

c++

syntax

new delete

or

::new ::delete

I'm wondering the uses of that :: as it seems works normally if I remove them.

These are all the codes written in tutorial of auto pointer.

#include <cstddef>  
size_t* alloc_counter(){
    return ::new size_t;  
}  
void dealloc_counter(size_t* ptr){
    ::delete ptr;  
}  
like image 422
PENGUINLIONG Avatar asked May 02 '15 11:05

PENGUINLIONG


2 Answers

You can override new for a class, but ::new will always seek in global scope. I.e.:

class A {
    void* operator new(std::size_t sz) { 
        /* 1 */ }
};

void* operator new(std::size_t sz) { 
        /* 2 */ }

void f() {
    A* a1 = new A;   // calls A::new (1)
    A* a2 = ::new A; // calls implementation 2 or compiler's new
}

That is described in § 5.3.4 New, clause 9:

If the new-expression begins with a unary :: operator, the allocation function’s name is looked up in the global scope. Otherwise, if the allocated type is a class type T or array thereof, the allocation function’s name is looked up in the scope of T. If this lookup fails to find the name, or if the allocated type is not a class type, the allocation function’s name is looked up in the global scope.

(as of N3797 draft)

Same applies to delete and ::delete

like image 180
myaut Avatar answered Oct 15 '22 10:10

myaut


::new and ::delete are the operators at the global scope. You use this syntax in case you overload new and delete for your class. In the latter case, calling simply new inside your overloaded new leads to infinite recursion, as you end up calling the operator you're just defining.

like image 22
vsoftco Avatar answered Oct 15 '22 08:10

vsoftco