gpt4 book ai didi

c++ - new/delete 和::new/::delete 有什么区别?

转载 作者:可可西里 更新时间:2023-11-01 15:51:11 24 4
gpt4 key购买 nike

new delete

::new ::delete

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

以上就是auto pointer教程中写的全部代码。

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

最佳答案

您可以为类覆盖 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

关于c++ - new/delete 和::new/::delete 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30001927/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com