我一直在尝试创建一个自定义分配器作为有趣的练习,但在创建数组时遇到了两个潜在问题。对于典型的分配调用,我将使用
1)分配器如何在不使用
2)如果我应该使用
malloc
和placement new
。然而,当我要创建一个数组时,我不知道该怎么做。首先,我注意到在某些地方,似乎像这里那样,placement new
可能对数组不安全。我也遇到了自己的错误,当我尝试对数组使用placement new
时,我会得到以下错误:
我理解了这个错误(我相信),但我更喜欢通过我的数组构造方法来解决这个错误。我有两个问题:`error C2679: binary '=' : no operator found which takes a right-hand operand of type 'SomeClass *' (or there is no acceptable conversion)
1)分配器如何在不使用
new[]
的情况下创建数组?是使用placement new
吗?如果是,那么上面提到的潜在危险怎么办?2)如果我应该使用
placement new
并在数组中调用它的每个元素,为什么我会得到上述错误?#include <stdio.h>
#include <new>
class SomeClass{
public:
SomeClass() {
printf("Constructed\n");
}
~SomeClass() {
printf("Destructed\n");
}
};
void* SomeAllocationFunction(size_t size) {
return malloc(size);
}
template<typename Type>
Type* SomeArrayAllocationFunction(size_t count){
Type* mem = (Type*)SomeAllocationFunction(sizeof(Type) * count);
for(unsigned int i = 0; i < count; ++i)
{
mem[i] = new(mem + i) Type();
}
return mem;
}
int main(void){
SomeClass* t = SomeArrayAllocationFunction<SomeClass>(2);
}
new(mem + i) Type();
似乎就是所需的全部了。然而,使用placement new
来分配数组是否危险呢?我发现有些地方认为它是危险的。 - mmurphyallocator<T>
向量将是一个更明显的解决方案。 - RedXvector
已经提供了这个解决方案。 - Mark B