zoukankan      html  css  js  c++  java
  • 【STL源码剖析读书笔记】自己实现简单的空间配置器MyAllocator

    MyAllocator.h

    #ifndef MY_ALLOCATOR_H
    #define MY_ALLOCATOR_H
    
    #include<new> //placement new
    #include<cstddef> //ptrdiff_t size_t
    //分配内存
    template<typename T>
    inline T* _allocator(ptrdiff_t n,T*){
    	T* temp = (T*)(::operator new((size_t)(n*sizeof(T))));
    	if (temp == 0){
    		cout << "out of memory" << endl;
    		exit(1);
    	}
    	return temp;
    }
    //释放内存
    template<typename T>
    inline void _deallocator(T* ptr){
    	::operator delete(ptr);
    }
    //构造对象
    template<typename T,typename V>
    inline void _construct(T* ptr, const V& value){
    	new (ptr) T(value); //定位new,在指定地址处构造对象
    }
    //析构对象
    template<typename T>
    inline void _destroy(T* ptr){
    	ptr->~T();
    }
    
    template<typename T>
    class MyAllocator{
    public:
    	//型别定义
    	typedef T value_type;
    	typedef T* pointer;
    	typedef const T* const_pointer;
    	typedef T& reference;
    	typedef const T& const_reference;
    	typedef size_t size_type;
    	typedef ptrdiff_t difference_type;
    	
    	template<class U>
    	struct rebind{
    		typedef MyAllocator<U> other;
    	};
    	pointer allocator(size_type n){
    		return _allocator((difference_type)n,(pointer)0);
    	}
    	void deallocator(pointer ptr){
    		_deallocator(ptr); 
    	}
    	void construct(pointer ptr, value_type value){
    		_construct(ptr, value);
    	}
    	void destroy(pointer ptr){
    		_destroy(ptr);
    	}
    	pointer address(reference x){
    		return (pointer)&x;
    	}
    	const_pointer address(reference x) const{
    		return (const_pointer)&x;
    	}
    	size_type max_type() const{
    		return size_type(UINT_MAX / sizeof(T));
    	}
    };
    
    #endif

    main.cpp

    #include "MyAllocator.h"
    #include<iostream>
    using namespace std;
    
    int main(){
    	MyAllocator<int> alloc;
    	int* ptr=alloc.allocator(2);
    	alloc.construct(ptr, 10);
    	alloc.construct(ptr+1, 8);
    	cout << *ptr << endl;
    	cout << ptr[1] << endl;
    	alloc.destroy(ptr);
    	alloc.destroy(ptr + 1);
    	alloc.deallocator(ptr);
    	
    	MyAllocator<int>::rebind<double>::other dalloc;
    	double* p = dalloc.allocator(2);
    	dalloc.construct(p, 3.5);
    	cout << *p << endl;
    	dalloc.destroy(p);
    	dalloc.deallocator(p);
    
    	system("pause");
    	return 0;
    }

  • 相关阅读:
    Asp.net导出Excel文件
    Ext.Net 使用总结之GridPanel中的选中行
    Ext.Net 使用总结之查询条件中的起始日期
    使用python crontab设置linux定时任务
    JSON Serialization/Deserialization in C#
    redis 基本数据类型-列表(List)
    redis 基本数据类型-字符串(String)
    使同一个server上不同port的django应用可在同一个浏览器上打开
    django server之间通过remote user 相互调用
    使用python实现短信PDU编码
  • 原文地址:https://www.cnblogs.com/ruan875417/p/4558293.html
Copyright © 2011-2022 走看看