我想尝试一下 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时如何实例化对象。