Override delete operator

前端 未结 3 496
有刺的猬
有刺的猬 2021-01-18 12:08

I want to override delete operator in my class. Here\'s what I am trying to do,but not succeeding.

class Complex{              
    void *operator new(size_t         


        
3条回答
  •  盖世英雄少女心
    2021-01-18 12:25

    Deleting through delete is quite strange, but deleting a void* is UB.

    Also, size_t is not a built-in type: it is define in .

    This can be fine:

    #include 
    
    class Complex
    {              
        void *operator new(size_t s);
        void operator delete(void *ptr);
    };
    
    void* Complex::operator new(size_t s)
    { return new char[s]; } //allocate a buffer of s bytes
    
    void Complex::operator delete(void *ptr)
    { delete[] static_cast(ptr); } //deallocate the buffer
    

    Practically, we allocate/deallocate a buffer of appropriate size coherently in new / delete.

    In new, we ask the system to give us the bytes we need. I used char[s] since char is the unit of memory size_t measures: sizeof(char) == 1 by definition.

    In delete we have to give back to the system the bytes identified by ptr. Since we allocated them as char[], we have to delete them as char[], hence the use of delete[] and the cast to char*.

提交回复
热议问题