SGI STL与用户的中间层接口

文章介绍了如何通过`simple_alloc`模板类封装C++标准库中的`default_alloc`,提供更简洁的内存分配和释放接口。同时,文中还展示了全局构造函数、销毁函数以及处理不同迭代器类型的`__destroy`函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

没错,就是把default_alloc再封装一层,交给用户使用。

#pragma once
#include "default_alloc.h"

template<typename T, typename Alloc>
class simple_alloc {
public:
	static T* allocate(size_t n) {
		return 0 == n ? 0 : (T*)Alloc::allocate(n * sizeof(T));
	}
	static T* allocate(void) {
		return (T*)Alloc::allocate(sizeof(T));
	}
	static void deallocate(T* p, size_t n) {
		if (0 != n) Alloc::deallocate(p, n * sizeof(T));
	}
	static void deallocate(T* p) {
		Alloc::deallocate(p, sizeof(T));
	}
};

还有就是几个全局函数,用来构造对象,为了简化代码直接用placement new了

#pragma once
#include <type_traits>

template<typename T1, typename T2>
inline void construct(T1* p, const T2& value) {
	new (p)T1(value);
}
template<typename T>
inline void destroy(T* pointer) {
	pointer->~T();
}
template<typename ForwardIterator>
inline void destroy(ForwardIterator first, ForwardIterator last) {
	typedef typename std::iterator_traits<ForwardIterator>::value_type value_type;
	__destroy(first, last, value_type);
}
template<typename ForwardIterator, typename T>
inline void __destroy(ForwardIterator first, ForwardIterator last, T) {
	typedef typename std::is_trivially_destructible<T> trival_destructor;
	__destroy_aux(first, last, trival_destructor());
}
template<typename ForwardIterator>
inline void __destroy_aux(ForwardIterator first, ForwardIterator last, std::true_type) {}

template<typename ForwardIterator>
inline void __destroy_aux(ForwardIterator first, ForwardIterator last, std::false_type) {
	for (; first < last; ++first)
		destroy(&*first);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值