ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

c – 为什么重载的new运算符是隐式静态的,并且构造对象不需要范围解析

2019-09-29 05:14:44  阅读:211  来源: 互联网

标签:c new-operator


为什么重载的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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有