C ++ memory management notes (a)

 

  C ++ memory allocation of four levels: 

  

  Four levels of comparison:

  

  Memory allocation and release of test:

    void* p1 = malloc(512);    //512 bytes
    free(p1);

    complex<int>* p2 = new complex<int>; //one object
    delete p2;             

    void* p3 = ::operator new(512); //512 bytes
    ::operator delete(p3);

// The following use allocators C ++ standard library.
// its interface, although standard, but did not achieve full compliance with the commercial; three form below come first. 
_MSC_VER #ifdef
     // The following two functions are non-static, to be given by calling object. The following three dispensing INTS. 
    Int * P4 = the allocator < int > () the allocate (. . 3 , ( int *) 0 );
    allocator<int>().deallocate(p4,3);           
#endif
#ifdef __BORLANDC__
    // The following two functions are non-static, scheduled to be called by the object. The following assignment 5 INTS. 
    Int * P4 = the allocator < int > () the allocate (. . 5 );  
    allocator<int>().deallocate(p4,5);       
#endif
#ifdef __GNUC__
    // The following two functions are static, can be obtained by calling the full name. The following bytes allocated 512.
     // void * P4 :: = the allocate the alloc (512); 
     // the alloc :: DEALLOCATE (p4,512);   
    
    // The following two functions are non-static, scheduled to be called by the object. The following assignment 7 INTS.     
    Void * P4 = the allocator < int > () the allocate (. . 7 );
    allocator<int>().deallocate((int*)p4,7);     
    
    // The following two functions are non-static, scheduled to be called by the object. The following assignment 9 INTS.     
    Void * P5 = __gnu_cxx :: __ pool_alloc < int > () the allocate (. . 9 );
    __gnu_cxx::__pool_alloc<int>().deallocate((int*)p5,9);    
#endif

  new keywords to achieve :

    First new compiler is compiled into three steps:

    With new = p * In (1.2);

    Equivalent to :

    void * mem = :: operator new (sizeof (Com)); // Memory allocation

    p = static_cast <Com *> (mem); // cast

    p-> Com :: Com (1,2); // constructor calls (himself so written on most compilers do not support, but in fact only achieve so prevents the compiler to write)

  We know that new memory is allocated by the operator new function implemented ().

  The operator new () function is actually implemented to rely, as shown malloc achieved:

  

  operator new () constantly circulating calling malloc (), should the unsuccessful allocate memory for words.

  But in fact there is another operation is to call _callnewh (size), this function can be overridden by us.

  当malloc也分配不出内存时,就会调用它,我们可以将其重写为 : 释放部分我们认为可以释放的内存,然后下次malloc就能分配到内存了。

  而 operator new() 还有第二个参数 : 默认为不报错,如若要报错可以自己指定。

  delete 关键字的实现 :

  

  如图所示 : delete 先调用其析构函数,然后再使用 operator delete()释放内存,而 operator delete其实只是简单地调用了free()。

Guess you like

Origin www.cnblogs.com/vizdl/p/12295026.html
Recommended