4

我想尝试一下 TBB 的可扩展分配器,但是当我不得不替换我的一些代码时感到很困惑。这是使用分配器完成分配的方式:

SomeClass* s = scalable_allocator<SomeClass>().allocate( sizeof(SomeClass) );

编辑:上面显示的不是使用可扩展分配器完成分配的方式。正如ymett 正确提到的,分配是这样完成的:

int numberOfObjectsToAllocateFor = 1;
SomeClass* s = scalable_allocator<SomeClass>().allocate( numberOfObjectsToAllocateFor );
scalable_allocator<SomeClass>().construct( s, SomeClass());
scalable_allocator<SomeClass>().destroy(s);
scalable_allocator<SomeClass>().deallocate(s, numberOfObjectsToAllocateFor);

这很像使用 malloc:

SomeClass* s = (SomeClass*) malloc (sizeof(SomeClass));

这是我要替换的代码:

SomeClass* SomeClass::Clone() const
{
   return new SomeClass(*this);
}//Clone

于是尝试了一个程序:

#include<iostream>
#include<cstdlib>
using namespace std;

class S
{
        public:
        int i;
        S() {cout<<"constructed"<<endl;}
        ~S() {cout<<"destructed"<<endl;}
        S(const S& s):i(s.i) {}
};

int main()
{
        S* s = (S*) malloc(sizeof(S));
        s = (S*) S();//this is obviously wrong
        free(s);
}

在这里我发现调用 malloc 不会实例化对象(我之前从未使用过 malloc )。所以在弄清楚如何传递*this给复制ctor之前,我想知道在使用malloc时如何实例化对象。

4

3 回答 3

21

placement newmalloc. _

void* mem = malloc(sizeof(S));
S* s = new (mem) S(); //this is the so called "placement new"

完成对象后,您必须确保显式调用其析构函数。

s->~S();
free(mem);
于 2011-02-10T11:09:56.513 回答
9

使用展示位置新

#include <memory>
//...
int main()
{
        S* s = (S*) malloc(sizeof(S));
        s = new (s) S();//placement new
        //...
        s->~S();
        free(s);
}
于 2011-02-10T11:08:07.030 回答
0

参数 toallocate()是对象的数量,而不是字节大小。然后调用分配器的construct()函数来构造对象。

scalable_allocator<SomeClass> sa;
SomeClass* s = sa.allocate(1);
sa.construct(s, SomeClass());
// ...
sa.destroy(s);
sa.deallocate(s);

如果想将它与标准库容器或其他 std 分配器感知类型一起使用,只需为其指定分配器类型。

std::vector<SomeClass, scalable_allocator<SomeClass>> v;
于 2011-02-10T14:26:48.947 回答