Is Stephen Lavavej#39;s Mallocator the same in C++11?(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.
这篇关于Stephen Lavavej 的 Mallocator 在 C++11 中是否相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Stephen Lavavej 的 Mallocator 在 C++11 中是否相同?
基础教程推荐
- 提升 ASIO 流缓冲 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- c++ STL设置差异 2022-01-01
