c++ - 使用 malloc() 和 free() 实现一个简单的分配器类

标签 c++ c++11 memory memory-management malloc

分配器的这种简单实现是否可以接受

template<typename T>
class Allocator
{
public:
    T * allocate(int n);  //allocate space for n objects of type T 
    void deallocate(T* p, int n);  //deallocate n objects of type T starting at p

    void construct(T* p, const T& v);  //construct a T with the value v in p
    void destroy(T* p);  //destroy the T in p
};

template<typename T>
T* Allocator<T>::allocate(int n)
{
    T* new_mem = (T*)malloc(n * sizeof(T));
    return new_mem;
}

template<typename T>
void Allocator<T>::construct(T* p, const T& v)
{
    T* constructed_object = new(p) T{ v };
}

template<typename T>
void Allocator<T>::deallocate(T* p, int n)
{
    for (int i = 0; i < n; ++i)
    {
        free(&p[i]);
    }
}

template<typename T>
void Allocator<T>::destroy(T* p)
{
    p->~T();
}

我将在 vector 中使用它来实现保留额外空间的功能,如下所示:

template<typename T, typename A>
void vector<T, A>::reserve(int newalloc)
{
    if (newalloc <= space)return;
    T* p = alloc.allocate(newalloc);
    for (int i = 0; i < sz; ++i)alloc.construct(&p[i], elem[i]);
    for (int i = 0; i < sz; ++i)alloc.destroy(&elem[i]);
    elem = p;
    space = newalloc;
}

哪里typename A = Allocator<T>alloc类型为 A . 我实现的分配器类的功能是否足以工作? (我觉得 deallocate 功能可疑)

最佳答案

您的释放函数确实不正确。 freemalloc 的规则很简单:您必须准确地将从 malloc 获得的指针传递给 free

template<typename T>
void Allocator<T>::deallocate(T* p, size_t)
{
    free(p);
}

请注意,您通常也应该将相同的指针 type 传递给释放函数,但在这种情况下,因为 free 只需要 void*作为参数,隐式转换将处理这个问题。

关于c++ - 使用 malloc() 和 free() 实现一个简单的分配器类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49466810/

相关文章:

函数体中没有使用c++成员函数参数,这是什么情况?

c++ - Visual 2015 上的 std::get_time 不会在不正确的日期失败

c++ - OpenMP:如何处理全局标准 vector 上的竞争条件

c++ - 理解关于 c++11 的省略规则

asp.net - 构建excel文件使内存异常

java - Java中如何确定对象的大小

memory - 为什么VkAccessFlagBits同时包含读位和写位?

c++ - 我的 Qt 程序显示带有标题的空白窗口

c++ - 在C++中格式化字符串的输出

c++ - 列出引用 : is GCC or Clang correct? 的初始化