STL: 自定义Allocator.

/*重构于 16/6/6 */

#include <iostream>
#include <vector>
#include <new>
#include <stdexcept>
#include <utility>

template<typename T>
class myAllocate {
public:
	using value_type = T;
	using pointer = T*;
	using const_pointer = const T*;
	using reference = T&;
	using const_reference = const T&;
	using size_type = std::size_t;
	using difference_type = std::ptrdiff_t;

	myAllocate() = default;

	template<typename Ty>
	myAllocate(const myAllocate<Ty>& other)noexcept;

	myAllocate(const myAllocate<T>& other)noexcept;

	~myAllocate() = default;

	myAllocate<T>& operator=(const myAllocate<T>& other)noexcept;

	template<typename Ty>
	myAllocate<T>& operator=(const myAllocate<Ty>& other)noexcept;

	T* allocate(const std::size_t& size);

	template<typename Ty>
	void constructor(T* ptr, Ty&& value);

	template<typename Type, typename ...Types>
	void constructor(T* ptr, Type&& value, Types&&... args);

	void deallocate(T* ptr, const std::size_t& size);

	template<typename Ty>
	void destroy(Ty* ptr);

	T* address(T& value);
	const T* address(const T& value)const;

};

template<typename T>
template<typename Ty>
myAllocate<T>::myAllocate(const myAllocate<Ty>& other)noexcept
{
	//
}

template<typename T>
myAllocate<T>::myAllocate(const myAllocate<T>& other)noexcept
{
	//
}

template<typename T>
template<typename Ty>
myAllocate<T>& myAllocate<T>::operator=(const myAllocate<Ty>& other)noexcept
{
	//
}

template<typename T>
myAllocate<T>& myAllocate<T>::operator=(const myAllocate<T>& other)noexcept
{

}


template<typename T>
T* myAllocate<T>::allocate(const std::size_t& size)
{
	if (size == 0) {
		return nullptr;

	}
	else {
		return new T[size];
	}
}

template<typename T>
template<typename Ty>
void myAllocate<T>::constructor(T* ptr, Ty&& value)
{
	if (ptr == nullptr) {
		throw std::bad_alloc{};

	} else {
		new(ptr) T(std::forward<Ty>(value));
	}
}

template<typename T>
template<typename Type, typename ...Types> //注意这里. meta.
void myAllocate<T>::constructor(T* ptr, Type&& value, Types&&... args)
{
	this->constructor(ptr++, value);
	this->constructor(ptr, std::forward<Types>(args)...);
}

template<typename T>
void myAllocate<T>::deallocate(T* ptr, const std::size_t& size)
{
	if (ptr == nullptr) {
		return;
	}

	if (size == 1) {
		delete ptr;
	}
	else {
		delete[] ptr;
	}
}

template<typename T>
template<typename Ty>
void myAllocate<T>::destroy(Ty* ptr)
{
	if (ptr = nullptr) {
		return;
	}

	ptr->~Ty();
}

template<typename T>
T* myAllocate<T>::address(T& value)
{
	return &value;
}

template<typename T>
const T* myAllocate<T>::address(const T& value)const
{
	return &value;
}

int main()
{


	return 0;
}

 

转载于:https://my.oschina.net/SHIHUAMarryMe/blog/683724

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值