没错,就是把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);
}