Stephen Lavavej的Mallocator在C++ 11中是一样的吗?

ein*_*ica 12 c++ containers allocator c++-standard-library c++11

8年前,Stephen Lavavej发表了这篇博客文章,其中包含一个名为"Mallocator"的简单分配器实现.从那时起,我们已经过渡到C++ 11时代(很快就会出现C++ 17)......新的语言特征和规则是否会影响Mallocator,或者它仍然是相关的?

Arn*_*aud 9

STL自己在2014年CppCon(从26'30开始)的STL功能和实现技术讲座中回答了这个问题.

幻灯片是在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);
  }
};
Run Code Online (Sandbox Code Playgroud)

请注意,它正确处理分配中可能出现的溢出.