美文网首页
关键字new和delete可以重载

关键字new和delete可以重载

作者: xiaoliang1 | 来源:发表于2020-06-28 19:50 被阅读0次

    代码如下:

    void test5() {
    
        Base *p1 = new Base;
        p1->a = 10;
        printf("0x%x\n", &(*p1));
        printf("%d\n", sizeof(*p1));
        
        delete p1;
    }
    

    这段代码可以用到关键字:new 和delete 关键字。但是貌似也可重写;具体入下:

    class Base
    {
    public:
        Base();
        ~Base();
        void operator delete(void* const block, size_t const) {
            printf("%s", __FUNCSIG__);
        }
    
        void*  operator new(size_t const size) {
            printf("%s", __FUNCSIG__);
            return NULL;
        }
        int a;
    
    private:
    
    };
    

    原来真的可以;
    delete底层是这样的:

    void __CRTDECL operator delete(void* const block) noexcept
    {
    0136C9E0  push        ebp  
    0136C9E1  mov         ebp,esp  
        #ifdef _DEBUG
        _free_dbg(block, _UNKNOWN_BLOCK);
    0136C9E3  push        0FFFFFFFFh  
        #ifdef _DEBUG
        _free_dbg(block, _UNKNOWN_BLOCK);
    0136C9E5  mov         eax,dword ptr [block]  
    0136C9E8  push        eax  
    0136C9E9  call        __free_dbg (0136172Bh)  
    0136C9EE  add         esp,8  
        #else
        free(block);
        #endif
    }
    

    居然用free,看来new是用malloc之流的C函数创建的;

    那么来了解下new 、构造函数、析构函数、deletel的调用顺序吧。代码如下:

    
    class Base
    {
    public:
        Base();
        ~Base();
        void operator delete(void* const block, size_t const) {
            printf("=====%d\n", sizeof(block));
            printf("%s\n", __FUNCSIG__);
    
            free(block);
        }
    
        void*  operator new(size_t const size) {
            printf("%s\n", __FUNCSIG__);
            void* ptr = malloc(size);
            memset(ptr, 0, size);
            return ptr;
        }
        int a;
    
    private:
    
    };
    
    Base::Base()
    {
        printf("%s\n", __FUNCSIG__);
    }
    
    Base::~Base()
    {
        printf("%s\n", __FUNCSIG__);
    }
    
    
    void test5() {
    
        Base *p1 = new Base;
        p1->a = 10;
        printf("0x%x\n", &(*p1));
        printf("%d\n", sizeof(*p1));
        delete p1;
    }
    
    
    
    int main()
    {
        test5();
        //Base p1=  test5();
        return EXIT_SUCCESS;
    }
    

    打印结果:

    void *__cdecl Base::operator new(const unsigned int)
    __thiscall Base::Base(void)
    0x5e0260
    4
    __thiscall Base::~Base(void)
    =====4
    void __cdecl Base::operator delete(void *const ,const unsigned int)
    

    。完事。
    我手动实现了new 和delete函数

    相关文章

      网友评论

          本文标题:关键字new和delete可以重载

          本文链接:https://www.haomeiwen.com/subject/viapfktx.html