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 中是否相同?
基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
