C++ Using the new operator efficiently

前端 未结 3 1216
时光取名叫无心
时光取名叫无心 2021-01-14 09:04

When instantiating a class with new. Instead of deleting the memory what kinds of benefits would we gain based on the reuse of the objects?

What is the process of n

3条回答
  •  耶瑟儿~
    2021-01-14 09:41

    If you new or delete an address it's marked as occupied or unassigned. The implementations do not talk all the time with the kernel. Bigger chucks of memory are reserved and divided in smaller chucks in user space within your application.

    Because new and delete are re-entrant (or thread-safe depending on the implementation) a context switch may occur but your implementation is thread-safe anyway while using the default new and delete.

    In C++ you are able to overwrite the new and delete operator, e.g. to place your memory management:

    #include  //declarations of malloc and free
    #include 
    #include 
    using namespace std;
    
    class C {
    public:
      C(); 
      void* operator new (size_t size); //implicitly declared as a static member function
      void operator delete (void *p); //implicitly declared as a static member function
    };
    
    void* C::operator new (size_t  size) throw (const char *){
      void * p = malloc(size);
      if (p == 0)  throw "allocation failure";  //instead of std::bad_alloc
      return p; 
    }
    
    void C::operator delete (void *p){  
      C* pc = static_cast(p); 
      free(p);  
    }
    
    int main() { 
       C *p = new C; // calls C::new
       delete p;  // calls C::delete
    }
    

提交回复
热议问题