【发布时间】:2011-02-10 11:03:16
【问题描述】:
我想试用 TBB 的可扩展分配器,但是当我不得不替换我的一些代码时感到困惑。 这是使用分配器完成分配的方式:
SomeClass* s = scalable_allocator<SomeClass>().allocate( sizeof(SomeClass) );
编辑:上面显示的并不是使用可扩展分配器完成分配的方式。作为ymett correctly mentioned,分配是这样完成的:
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 时如何实例化对象。
【问题讨论】:
-
为什么不覆盖
operator new为您感兴趣的课程或只是全局课程? -
@sharptooth:这是个好主意,但现在,我只是在测试scalable_allocator 是否真的有助于避免堆争用。如果测试成功,覆盖 new 肯定会派上用场。谢谢:)
-
如果分配器符合标准,它应该有构造和销毁方法:cplusplus.com/reference/std/memory/allocator/construct
-
覆盖
operator new()更快、更可靠——你只需这样做并重新编译,看看它是否有帮助,你不需要更改调用代码——它会立即在任何地方生效。
标签: c++ memory-management malloc new-operator tbb