8年前,斯蒂芬拉瓦维出版 这篇博文 包含一个简单的allocator实现,名为“Mallocator”。从那时起,我们已经过渡到C ++ 11时代(很快就会出现C ++ 17)......新的语言特性和规则是否会影响Mallocator,或者它仍然是相关的?
8年前,斯蒂芬拉瓦维出版 这篇博文 包含一个简单的allocator实现,名为“Mallocator”。从那时起,我们已经过渡到C ++ 11时代(很快就会出现C ++ 17)......新的语言特性和规则是否会影响Mallocator,或者它仍然是相关的?
STL本人对他的这个问题有了答案 STL功能和实现技术 在CppCon 2014上讲话(从26'30开始)。
该 幻灯片 在github上。
我合并了以下幻灯片28和29的内容:
#include <stdlib.h> // size_t, malloc, free
#include <new> // bad_alloc, bad_array_new_length
template <class T> struct Mallocator {
typedef T value_type;
Mallocator() noexcept { } // default ctor not required
template <class U> Mallocator(const Mallocator<U>&) noexcept { }
template <class U> bool operator==(
const Mallocator<U>&) const noexcept { return true; }
template <class U> bool operator!=(
const Mallocator<U>&) const noexcept { return false; }
T * allocate(const size_t n) const {
if (n == 0) { return nullptr; }
if (n > static_cast<size_t>(-1) / sizeof(T)) {
throw std::bad_array_new_length();
}
void * const pv = malloc(n * sizeof(T));
if (!pv) { throw std::bad_alloc(); }
return static_cast<T *>(pv);
}
void deallocate(T * const p, size_t) const noexcept {
free(p);
}
};
请注意,它正确处理分配中可能出现的溢出。
正如@kerrek建议的那样,这里有一个基于的Mallocator 关联 竞技场分配器与竞技场部分删除。
template<class T>
struct Mallocator11 {
using value_type = T;
using pointer = T*;
using propagate_on_container_copy_assignment = std::true_type;
using propagate_on_container_move_assignment = std::true_type;
using propagate_on_container_swap = std::true_type;
Mallocator11(Mallocator11 const&) = default;
Mallocator11& operator=(Mallocator11 const&) = default;
Mallocator11()=default;
template<class U>
Mallocator11(Mallocator11<U> const&) noexcept {}
template<class U>
Mallocator11& operator=(Mallocator11<U> const&) noexcept {return *this}
pointer allocate(std::size_t n) {
if (std::size_t(-1) / sizeof(T) < n)
throw std::bad_array_new_length(); // or something else
if (!n) return nullptr; // zero means null, not throw
if(auto*r= static_cast<pointer>(malloc(n * sizeof(T))))
return r;
throw std::bad_alloc();
}
void deallocate(pointer p, std::size_t n) {
free(p);
}
template<class U>
bool operator==(Mallocator11<U> const& rhs) const {
return true;
}
template<class U>
bool operator!=(Mallocator11<U> const& rhs) const {
return false;
}
};
代码少了很多。传播的一些特征。