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 中是否相同?
基础教程推荐
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17