【问题标题】:Implementing a simple allocator class using malloc() and free()使用 malloc() 和 free() 实现一个简单的分配器类
【发布时间】:2018-03-24 15:59:24
【问题描述】:

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

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();
}

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

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&lt;T&gt; 和alloc 的类型为A。 我实现的分配器类的功能是否足以工作? (我觉得deallocate这个功能很可疑)

【问题讨论】:

  • 我猜安置新的回报void*可能不会碰巧是T*。

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


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    不,这行不通。

    • 你应该有一个rebind 方法。

    • 您需要提供比较运算符(== 和!=)

    • 您的 allocate 方法分配过多。当它到达你的时候,sizeof(T) 已经发生了。

    • 您的deallocate 方法是错误的。你得到一个指针。第二个参数是分配大小的提示。

    • construct 和 destruct 方法是可选的。如果您不提供,它们将由allocator_traits 为您合成。

    有关最小分配器的示例,请参阅 https://github.com/llvm-mirror/libcxx/blob/5a424a985612452d4f7a3f02422207456d54a53e/test/support/min_allocator.h#L21(尽管没有 rebind)

    【讨论】:

    • 分配函数正确。您的链接证实了这一点。
    猜你喜欢
    • 2010-10-25
    • 2012-01-18
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多