Step by step writing STL: Space configurator (1)

Source: Internet
Author: User

Hou Jie said: Tracking first-class programs, absorbing nutrients from them, and imitating the programs he wrote are much more valuable than the third-stream programs that he thinks he is trying to write, at least I think so-99.999% of the world's programs are at the bottom of the three streams in front of STL!

 

Mr Hou Jie's comment on STL is too high. He used to be familiar with STL and knew a little about the principle. Due to his influence, he decided to study STL source code, at the very beginning, I had to record the process and try to use the principles of the standard library to write a complete imitation STL. I think this is a huge project, it involves advanced data structures, powerful algorithms, generic programming thinking, STL mastery, powerful C ++ coding level, complex hierarchy inheritance, and type extraction technology, I believe this process will benefit a lot! After all, I was a sophomore, so I had to wait for a while. I want to finish this project during my undergraduate course. I have no regrets!

 

It is the hierarchical distribution chart of STL. Of course, there are still some components, such as numerical processing, pair peer groups, String, smart pointers, and valarray arrays. The implementation difficulties are mainly concentrated in several places, the implementation of the map red/black tree, heap algorithm system, function adapter, and stream iterator respectively. In particular, the internal implementation of the function adapter is an exclusive use of all the top skills. I start with the leftmost memory Distributor because it is the core of all the functions!

 

 

There is no stranger to the memory distributor. For example, each operating system has its own memory distributor, and Ace has an ace_allow.r distributor, so the same is true for STL. Its memory distributor (space configurator) it plays an abnormal and important role in the standard library. All memory allocation, management, and release are controlled by him. The SGI design concept is to remove the red-light area of memory management, passed as template parameters to each container

Due to the large number of STL implementation versions, I first provided an available API for the distributor, referring to the STL implementation version of Microsoft rather than the SGI version, but it is undoubtedly a good entry point!

For example, in vector:

Template <class T, class alloc <t> = Allocator <t>

Class vector .........

He uses the built-in default memory distributor. In this example, we can see that there are two splitters. This is an advanced feature in sgi stl. It implements multi-level memory allocation and uses the memory pool to achieve efficiency optimization, it also reduces the possibility of memory fragmentation.

Before that, you need to know two global functions: Operator new and: Operator Delete. Be sure not to confuse them with general new Delete, our new operator calls the object's constructor to initialize the memory when allocating the memory. However, operator new only allocates the memory and does not call the constructor, this is the key to implementing a non-initialized memory pool, and the same is true for Delete.

In addition, you also need to understand the placement new operator. It is a positioning operator and does not allocate memory. It only locates in a allocated area!

Here we first implement a distributor class that can interface with the standard container. It is not clever, but it reflects the necessary features of the standard distributor, in fact, from a certain point of view, it is the appearance of the SGI level-1 distributor. When SGI is used internally, it malloc and makes some necessary measures and optimizations:

Template <class _ ty> struct allocator_base {// configurator base class typedef _ ty value_type ;}; template <class _ ty> struct allocator_base <const _ ty> {// The Configurator is specially applied to the const base class typedef _ ty value_type;}; Template <class _ ty> class Allocator: public allocator_base <_ ty> {public: // The internal type typedef typename STD: size_t size_type; typedef typename STD: ptrdiff_t difference_type; typedef _ ty * pointer; typedef const _ ty * const_pointer; typedef _ ty & ref Erence; typedef const _ ty & const_reference; typedef allocator_base <_ ty> _ mybase; typedef typename _ mybase: value_type; // configurator type conversion template <class _ other> struct rebind {typedef Allocator <_ other> Other ;}; // address Function Definition pointer address (reference value) const {return & value;} const_pointer address (const_reference value) const {return (const_pointer) & Value:} // default constructor does nothing at all Allocator () Throw () {}// default replication structure Allocator (Const Allocator &) Throw () {}// copy and construct a template <class _ otherall> Allocator (const Allocator <_ otherall> &) Throw () {} // destructor ~ Allocator () Throw () {}// return the maximum memory size_type max_size () const throw () {// use the numeric function numeric_limit <size_type >:: max () /sizeof (_ ty);} // allocate unconstructed memory to Use Pointer allocate (size_type num, typename Allocator <void >:: const_pointer hint = 0) {return (pointer) (: Operator new (Num * sizeof (_ ty);} // construct the void construct (pointer P, const_reference value) in the memory {New (P) _ ty (value);} // The Void destroy (pointer p) {P-> ~ object in the Destructor memory ~ _ Ty ();} void deallocate (pointer P, size_type size) {: Operator Delete (p) ;}// in order to comply with the standard configurator, only true can be returned here, only falsebool operator == (Allocator const & A) const {return true;} bool operator can be returned next time! = (Allocator const & A) const {return! Operator = (a) ;}}; // the Allocator template is specific to the class template of the type void <> class Allocator <void> {public: typedef void _ ty; typedef _ ty * pointer; typedef const _ ty * const_pointer; typedef _ ty value_type; Template <class _ other> struct rebind {typedef Allocator <_ other> Other;}; Allocator () throw () {// still the same, do nothing} Allocator (const Allocator <_ ty> &) Throw () {// copy the structure, nothing else} template <class _ other> Allocator (const Allocator <_ other> &) Throw () {} template <class _ other> Allocator <_ ty> & operator = (const Allocator <_ other> &) {return (* This );}};

There are two base classes at the beginning. These two base classes have no members and only one built-in type. These two base classes are not required and can be skipped. They only reflect a good design, the last class is a special void type for the template. This is just to avoid undefined behavior when using void, from this point, we can see that STL has fully predicted various possible situations. We mainly look at the allocator class!

At the beginning, a pair of typedef was defined, which defined a bunch of built-in types for the distributor class. In fact, they can also be not defined, but they are defined in STL to create a unified type, ease of management and readability

Next

Template <class _ other>

Struct rebind

{

Typedef Allocator <_ other> Other;

};

This is a distributor conversion method, which can be easily converted to another type of service distributor. For example, we construct a t class. If you need to construct a T *, you can use this method.

Allocator <t >:: rebind <t * >:: other pallocator;

In this way, pallocator is a T * service distributor. For more information, see STL standard library.

 

The subsequent functions of this class are required by the standard interface and cannot be less than one. The change is the four allocate deallocate destory construct.

The allocate function allocates a continuous list of unconstructed spaces for backup,

The deallocate function releases space.

The construct function call layout is new, and the constructor is called at the same time. The object is located at the specified position by new.

The destory function calls the destructor,

These functions are highly variable. For example, if we create a Student Score Management System, we need to construct a student class, that is, we need to obtain data from the database to initialize student objects, then you can embed SQL statements in construct. In the container where you hold the student object, the data source obtained is not input from the keyboard (parameter input ), instead, it is automatically obtained from the database. This is not very convenient! Similarly, several other functions,

This alignment is very simple, so we only need to pay attention to those points. Therefore, when writing our alignment and the interface with the standard container, we need to provide the appropriate interface.

 

This Allocator will be used in the future as the entry point of the sgi stl version. For how to optimize it, the next section will be written!

Now we can write a small program to test it:

#include <iostream>#include <list>#include <vector>#include <algorithm>#include "allocator.h"using namespace std;int _tmain(int argc, _TCHAR* argv[]){std::vector<double,Allocator<double> > vec_double;std::list<int,Allocator<int> > list_int;for(int i=0;i<60;i++){list_int.push_back(i);vec_double.push_back( double(i)/3 );}list<int,Allocator<int> >::iterator it = list_int.begin();vector<double,Allocator<double> >::iterator io = vec_double.begin();cout<<"list test:"<<endl;for(; it!= list_int.end();++it)cout<<*it<<" ";cout<<endl<<endl;cout<<"vector test:"<<endl;for(;io!= vec_double.end();++io)cout<<*io<<" ";system("pause");return 0;}

 

 

 

 

 

 

 

 

 

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.