STL Memory Management

Source: Internet
Author: User

Chinese New Year at home nothing to see the "STL Source Analysis", the school will see the things summed up, in case forget.

Start with a summary of the STL's memory management. In charge of STL memory control is a thing called Space adapter (alloc). The STL has two space adapters, the SGI standard Space adapter (allocate), and the SGI Special Space Adapter (ALLOC), which simply encapsulates new and delete C + +. The following is mainly about the Alloc space adapter.

In general, the memory configuration and release operations of C + + are:

class Foo {...} FooNew  foo;delete PF;

Where the new operator contains two stages: 1, operator new configuration space, 2, call Foo constructor constructs the content. Similarly, the delete operator also contains two procedures for calling destructors and freeing space. STL memory management refers to this approach, separating the spatial configuration from the construction content. Memory configuration and memory release are the responsibility of Alloc::allocate () and Alloc::d eallocate (), which are responsible for the construction and destruction of objects, respectively, by Alloc::construct () and Alloc::d Estroy ().

The construct () and destroy () functions are described below.

Template <classclass t2>voidconst t2& value) {   New // here, new is placement new, which is an overloaded version of operator new, calling only the constructor of the object and not allocating memory. Operator New says, there are two steps.   }
Template <class t>void destroy (t* pointer) {    pointer// Call destructor }

As you can see from the code, the Alloc::construct () and alloc: the:d Estroy () function is the encapsulation of the constructor T () and the destructor ~t (), which are responsible for object construction and destruction. ( Note: The above code does not involve any memory configuration and deallocation, simply calling constructors and destructors, which is why constructor () is using placement new instead of operator new. In addition, Alloc overloads the second version of Alloc::d Estroy (), accepts two iterator parameters, is used for bulk destructor, and uses type_traits programming techniques to determine if an object has tirvial destructor to determine if the call destroy function needs to be displayed to speed up the batch destructor. In short, type_traits is a generalization of the method to extract the object's type information, to determine whether the object has trivial destructor,trivial destructor now you can understand that there is no display to define the destructor, For example, the system built-in int variable, after waiting for time to summarize the implementation of type_traits and iterator_traits principle.

The second part of the memory configuration is summarized----the construction and destruction of the object, and the first part----the configuration and release of the space are summarized below.

SGI completes memory configuration and deallocation with malloc () and free (). In order to solve the memory fragmentation problem that can be caused by small chunks, SGI designed a two-tier Configurator, the first level uses malloc () and free () to configure and release the memory space, the second level Configurator adopts the following strategy: When the configuration chunk exceeds bytes, it is considered large enough to call the first level configurator , when it is less than bytes, the memory pool is used as the finishing method. The following mainly summarizes the second level configurator.

As mentioned earlier, the SGI second-level Configurator has the following strategy: If the chunk is large enough to exceed bytes, the first-level configurator is transferred. When the chunk is less than bytes, the memory pool management----each configuration of a large chunk of RAM, the corresponding maintenance of a free list (free-list). The next time you have the same size memory requirements, take it directly from the free-list, and when the memory is released, it is recycled into the free-list. The second-level Configurator maintains 16 free-list, each of which manages 8,16,24...128 bytes-sized chunks, and the chunks that the client requests are automatically resized to the above size, such as the bytes adjustment to the bytes. Here is the node for the free-list.

Union obj{    Union obj* free_list_link;    Char client_data[1];  // The client sees this field     }

The reason for this is that the union is used to save space, the variables in the Union share the same storage space, and obj stores an address that points to the next available chunk, and the first byte of that chunk is obj, and that address also points to the next obj. It can be understood that the first byte of the available chunks make up a list, maintaining the same size of chunks, and the address of the first chunk is placed in the free-list. The Chunk_alloc () function requests space from the memory pool when there is no usable chunk for a chunk of a size in free-list. The above summary may not be so intuitive, the following part of the code specifically explained. Because the code is more, so only select the key code attached to their own understanding, all the code can refer to the STL source analysis. Note: The use of the Union in the source code is only to save space, but now the memory size is not a major concern for people, and in addition to the Union in the actual use of a variety of strange problems, so most of the time it is recommended to have a struct instead.

//__nfreelists = = 16 represents 16 Free_list maintained by the Configurator, and volatile means that the compiler is not allowed to optimize free_list variables; free_list has the address of obj, That is, the first chunk that can be used under this size.  staticvolatile free_list[__nfreelists];
Static void*Allocate (size_t N) {obj*volatile* MY_FREE_LIST;//It's a pointer to obj*.obj *result; //call the first level adapter if it is greater than 128  if(N >(size_t) __max_bytes) {      return(Malloc_alloc::allocate (n)); }  //found 16 of the appropriate free_listMy_free_list = Free_list +Freelist_index (n); Result= *my_free_list; if(Result = =0){    //if no available free_list are found, prepare to repopulate free_list    void*r =Refill (ROUND_UP (n)); returnR; }  *my_free_list = result--Free_list_link;//here is the key to understanding, in fact, the result has been pointed to the first available block, the first byte of the block is the next available block is the next one of the address of obj, so this sentence has removed the first available block.   returnresult;}

The Space release function deallocate () first to determine whether greater than bytes, greater than by the first level of the Configurator processing, less than to find the corresponding free_list will be retracted. After understanding the code of allocate (), the key code inside the deallocate () is not difficult to understand:

My_free_list = free_list +//  Q points to the chunk to be retracted *my_free_list = q;

The refill () function to repopulate free_list is to use the Chunk_alloc function to remove new space from the memory pool (default to 20 new chunks of a certain size, such as insufficient memory pool space or possibly less than 20), and construct a linked list to hang in the current size of the Free_ List behind. After understanding the concept that the first byte of the new chunk is the next chunk and the address of the next obj, the code for refill () is not difficult to understand, so the code is not posted below.

The Chunk_alloc () function, which has been mentioned before, is to take space from the memory pool for free_list. Its logic is that if the memory pool space to fully meet the requirements, then the Free_list configuration 20 new chunks, if the memory pool remaining space does not fully meet the demand, but enough to supply one or more chunks, the free_list configured to the number of chunks in its capacity, If the remaining space in the memory pool cannot be satisfied, the remaining fraction in the memory pool is allocated to the appropriate free_list, then the unused chunks in the free_list that maintain the larger chunks are released, and the space is returned to the memory pool for the memory pool to allocate space for the current free_list. If, at the same moment, there is no memory everywhere, then can only resort to the first level configurator, if he can not make it, it will only throw an exception. The Chunk_alloc code is not difficult to understand, based on the understanding of the preceding code.

The five STL global functions are also described later in this chapter for use in uninitialized spaces, which facilitates subsequent container implementations.

STL Memory Management is basically the case, mainly using malloc and free to configure the memory, and so look back to see the Tcmalloc malloc and free improvements again.

STL Memory Management

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.