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;
}
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 typeT
or array thereof, the allocation function’s name is looked up in the scope ofT
. 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
::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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With