分配器的这种简单实现是否可以接受
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
功能可疑)
最佳答案
您的释放函数确实不正确。 free
和 malloc
的规则很简单:您必须准确地将从 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/