Is Stephen Lavavej's Mallocator the same in C++11?

前端 未结 2 1682
抹茶落季
抹茶落季 2021-02-07 23:41

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

2条回答
  •  悲&欢浪女
    2021-02-08 00:19

    As @kerrek suggested, here is a Mallocator that is based off the linked arena allocator with the arena part deleted.

    template
    struct Mallocator11 {
      using value_type = T;
      using pointer = T*;
      using propagate_on_container_copy_assignment = std::true_type;
      using propagate_on_container_move_assignment = std::true_type;
      using propagate_on_container_swap = std::true_type;
    
      Mallocator11(Mallocator11 const&) = default;
      Mallocator11& operator=(Mallocator11 const&) = default;
      Mallocator11()=default;
      template
      Mallocator11(Mallocator11 const&) noexcept {}
      template
      Mallocator11& operator=(Mallocator11 const&) noexcept {return *this}
    
    
      pointer allocate(std::size_t n) {
        if (std::size_t(-1) / sizeof(T) < n)
          throw std::bad_array_new_length(); // or something else
        if (!n) return nullptr; // zero means null, not throw
        if(auto*r= static_cast(malloc(n * sizeof(T))))
          return r;
        throw std::bad_alloc();
      }
      void deallocate(pointer p, std::size_t n) {
        free(p);
      }
      template
      bool operator==(Mallocator11 const& rhs) const {
        return true;
      }
      template
      bool operator!=(Mallocator11 const& rhs) const {
        return false;
      }
    };
    

    Lots less code. Some traits for propogation.

提交回复
热议问题