为什么重载new运算符是隐式静态的,并且不需要构造对象的范围解析 [英] Why overloaded new operator is implicitly static and no scope resolution required to construct the object

查看:160
本文介绍了为什么重载new运算符是隐式静态的,并且不需要构造对象的范围解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么重载的new运算符是隐式静态的,以及我们如何通过调用没有范围解析运算符的重载的new运算符来分配内存?

Why overloaded new operator is implicitly static and how we are able to allocate memory by calling overloaded new operator without scope resolution operator?

在我看来,如果某些东西是静态的然后我们可以通过类名在main中调用它。

In my view if something is static then we can call it in main by through class name.

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;
}


推荐答案

草稿C ++标准部分中说5.3.4 New 段落 9 中,如果 new表达式不是以开头: :,然后在它们首先输入的范围内查找,然后在全局范围内找不到:

The draft C++ standard says in section 5.3.4 New paragraph 9 that if the new expression does not begin with :: then it is looked up in the scope of they type first and then if not found globally:


如果new-expression以一元::运算符开头,在全局范围内查找分配
函数的名称。否则,如果
分配的类型是类类型T或其数组,则在T的范围内查找分配
函数的名称。如果此查找未能使
查找名称,或者如果分配的类型不是类类型,则在全局范围内查找
分配函数的名称

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 to why it is implicitly static, it seems like it would be inconvenient restriction to require an instance of the type in order to invoke the member allocation function. It seems like would also require different syntax since how would the compiler know which instance to use which would make things messy.

成员分配函数隐式静态的事实已得到覆盖。在 12.5 免费存储部分:

The fact that member allocation functions are implicitly static is covered in section 12.5 Free store:


任何分配T类的函数是静态成员(即使不是
显式声明为静态)。

Any allocation function for a class T is a static member (even if not explicitly declared static).

这篇关于为什么重载new运算符是隐式静态的,并且不需要构造对象的范围解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆