new/delete 和 ::new/::delete 有什么区别?

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

new delete

::new ::delete

我想知道 :: 的用途,因为如果我删除它们,它似乎可以正常工作。

以上就是自动指针教程中写的全部代码

#include <cstddef>  
size_t* alloc_counter(){
    return ::new size_t;  
}  
void dealloc_counter(size_t* ptr){
    ::delete ptr;  
}  

::new::delete 是全局范围内的运算符。如果您为 class 重载 newdelete,则可以使用此语法。在后一种情况下,在重载的 new 中简单地调用 new 会导致无限递归,因为您最终会调用您刚刚定义的运算符。

您可以为 class 覆盖 new,但 ::new 将始终在全局范围内搜索。即:

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
}

在 § 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.

(截至 N3797 草案)

同样适用于 delete::delete