Today again read the "STL Source code Analysis", can not help but praise STL Design classic. STL Space adaptation code design is particularly incisive, not only take into account the hidden trouble of memory fragments, but also take into account the thrift and reuse of pointer space, reduce maintenance chain list (lists) brings additional burden. Let's take a look at the following code;
First look at the STL structure,
Union obj{
Union obj *free_list_link;
Char clent_data[1]; /* The client sees this *
/};
OBJ uses union, because of Union, from its first field view, obj can be treated as a pointer to another obj of the same form. From its second field view, obj can be treated as a pointer to the actual area. The result of one thing and two is that there is not another kind of cost of memory that would be required to maintain a list of pointers.
Take a look at the sample code below and you'll find the subtleties of its design.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <iostream> using namespace
Std
Union obj{Union obj *free_list_link; Char clent_data[1];
/* The client sees this */};
int main () {obj *OP1 = (obj *) malloc (32);
strcpy (Op1->clent_data, "Hello free!");
obj *op2 = (obj *) malloc (32);
Op2->free_list_link = NULL;
obj *op3 = (obj *) malloc (32);
strcpy (op3->clent_data, "Hello free L");
printf ("----------------------------------------\ r \ n");
printf ("Address freelist:%ld\r\n", (long) (Op3->free_list_link));
printf ("Address clentdata:%ld\r\n", (Long) & (Op3->clent_data));
obj *OP4 = (obj *) malloc (32);
Op4->free_list_link = OP2;
obj *OP5 = (obj *) malloc (32);
Op5->free_list_link = OP4;
printf ("----------------------------------------\ r \ n");
obj *begin = OP5;
while (begin) {printf ("%ld\r\n", (long) begin);
Begin = begin->free_list_link;
} /* Release OP3 * * op2->free_list_link = OP3;
Op3->free_list_link = NULL;
printf ("----------------------------------------\ r \ n");
printf ("Address freelist:%ld\r\n", (long) (Op3->free_list_link));
printf ("Address clentdata:%ld\r\n", (Long) & (Op3->clent_data));
printf ("----------------------------------------\ r \ n");
begin = OP5;
while (begin) {printf ("begin:%ld\r\n", (long) begin);
Begin = begin->free_list_link;
return 0;
}
The output is as follows:
----------------------------------------
Address freelist:1819043176
Address clentdata:143143000
----------------------------------------
143143080
143143040
143142960
----------------------------------------
Address freelist:0
Address clentdata:143143000
----------------------------------------
begin:143143080
begin:143143040
begin:143142960
begin:143143000