c – 为什么重载的new运算符是隐式静态的,并且构造对象不需要范围解析
作者:互联网
为什么重载的new运算符是隐式静态的,以及我们如何通过在没有作用域解析运算符的情况下调用重载的new运算符来分配内存?
在我看来,如果某些东西是静态的,那么我们可以通过类名称在main中调用它.
class xyz
{
void* operator new (size_t size); //implicitly declared static
void operator delete (void *p); //implicitly declared static
};
int main()
{
C *p = new C;
delete p;
}
解决方法:
draft C++ standard在第5.3.4节新的第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
至于为什么它是隐式静态的,为了调用成员分配函数,似乎需要一个类型的实例是不方便的限制.似乎还需要不同的语法,因为编译器如何知道使用哪个实例会使事情变得混乱.
第12.5节免费存储中介绍了成员分配函数是隐式静态的事实:
Any allocation function for a class T is a static member (even if not
explicitly declared static).
标签:c,new-operator 来源: https://codeday.me/bug/20190929/1830712.html