Stephen Lavavej 的 Mallocator 在 C++11 中是否相同?
8 年前,Stephen Lavavej 发表了这篇博文,其中包含简单的分配器实现,命名为Mallocator".从那时起,我们已经过渡到 C++11(以及很快的 C++17)时代......新的语言特性和规则是否会影响 Mallocator,还是仍然相关?
8 years ago, Stephen Lavavej published this blog post containing a simple allocator implementation, named the "Mallocator". Since then we've transitioned to the era of C++11 (and soon C++17) ... does the new language features and rules affect the Mallocator at all, or is it still relevant as is?
推荐答案
STL 自己在他的 STL 中有这个问题的答案特性和实现技术在 CppCon 2014 上的演讲(开始于 26'30).
STL himself has an answer to this question in his STL Features and Implementation techniques talk at CppCon 2014 (Starting at 26'30).
幻灯片在github上.
我合并了下面幻灯片28和29的内容:
I merged the content of slides 28 and 29 below:
#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);
}
};
请注意,它正确处理了分配中可能出现的溢出.
Note that it handles correctly the possible overflow in allocate.
相关文章