zoukankan      html  css  js  c++  java
  • 3.不同编译器的分配器实现

    VC6编译器的实现

    std::allocator实现如下:

      VC6的allocator只是以::operator new和::operator delete完成allocate()和deallocate(),没有任何特殊设计。以元素为单位,而后面有个编译器的实现是以字节为单位的。

    #include <iostream>
    
    template<class _Ty>inline 
    _Ty *_Allocate(_ptrdiff_t _N, _Ty*) {
    	if (_N < 0) _N = 0;
    	return ((_Ty*))operator new((size_t)_N * sizeof(_Ty)));
    }
    
    
    template<class _Ty>
    class allocator {
    public:
    	typedef size_t size_type;
    	typedef ptrdiff_t difference_type;
    	typedef _Ty *pointer;
    	typedef _Ty value_type;
    	pointer allocate(size_type _N, const void*) {
    		return (_Allocate((difference_type)_N, (poiter)0));
    	}
    };
    
    //Vc6 所有容器中的第二个默认模板参数都是allocator
    template <class _Ty>
    class _A = allocator<_Ty>
    	class list
    
    

    BC5编译分配器实现

    与VC6相同,也是对operator new和operator delete封装了一次,并没有大的改进。

    G2.9标准分配器实现

    G2.9到了G4.9就成了标准库之外的pool_alloc。

    G2.9的allocator只是以::operator new和operator delete完成allocator()和deallocator(),没有任何特殊设计。

    G2.9容器使用的分配器,不是std::allocator而是std::alloc

    #include <iostream>
    template<class T>
    class allocator {
    public:
    	typedef T value_type;
    	typedef T* pointer;
    	typedef size_t size_type;
    	typedef ptrdiff_t difference_type;
    	pointer allocate(size_type n) {
    		return ::allocate((difference_type)n, (pointer)0);
    	}
    	void deallocate(pointer p) { ::deallocate(p); }
    };
    
    template <class T>
    inline T* allocate(ptrdiff_t size, T*) {
    	set_new_handler(0);
    	T* tmp = (T*)(::operator new((size_t)(size * sizeof(T))));
    	if (tmp == 0) {
    		cerr << "out of memory" << std::endl;
    		exit(1);
    	}
    	return tmp;
    }
    
    template<class T>
    inline void deallocate(T* buffer) {
    	::operator delete(buffer);
    }
    
    

    G4.9标准分配器实现

    G4.9的allocator只是以::operator new和::operator delete完成allocate()和deallocate

    #include <iostream>
    template <typename _Tp>
    class new_allocator {
    	pointer allocate(size_type _n, const void* = 0) {
    		if (_n > this->max_size())
    			std::__throw_bad_alloc();
    		return static_cast<_Tp*>(::operator new(_n * sizeof(_Tp)));
    	}
    
    	void deallocate(pointer _p, size_type) {
    		::operator delete (_p);
    	}
    };
    

    G2.9std::alloc运行模式

    容器申请内存发生,先看看pool内有没有余量,如果有就在内存池中分配出20个链表,如果内存池中没有余量,就将剩余的内存进行碎片化处理,然后重新malloc。

  • 相关阅读:
    Linux程序的执行
    Linux图形操作与命令行
    Linux网络配置
    Zip文件中文乱码问题解决方法(MAC->Windows)
    我只是一直很努力
    Android抓包方法(三)之Win7笔记本Wifi热点+WireShark工具
    Android抓包方法(二)之Tcpdump命令+Wireshark
    Android抓包方法(一)之Fiddler代理
    Android反编译(二)之反编译XML资源文件
    Android反编译(一)之反编译JAVA源码
  • 原文地址:https://www.cnblogs.com/ccpang/p/12235411.html
Copyright © 2011-2022 走看看