使用malloc而不是new,并在创建对象时调用复制构造函数

Nav*_*Nav 4 c++ malloc memory-management tbb new-operator

我想尝试TBB的scalable_allocator,但在我不得不替换我的一些代码时感到困惑.这是分配器的分配方式:

SomeClass* s = scalable_allocator<SomeClass>().allocate( sizeof(SomeClass) );
Run Code Online (Sandbox Code Playgroud)

编辑:上面显示的不是如何使用scalable_allocator完成分配.正如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);
Run Code Online (Sandbox Code Playgroud)

这很像使用malloc:

SomeClass* s = (SomeClass*) malloc (sizeof(SomeClass));
Run Code Online (Sandbox Code Playgroud)

这是我想要替换的代码:

SomeClass* SomeClass::Clone() const
{
   return new SomeClass(*this);
}//Clone
Run Code Online (Sandbox Code Playgroud)

所以尝试了一个程序:

#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);
}
Run Code Online (Sandbox Code Playgroud)

在这里我发现调用malloc不会实例化对象(我之前从未使用过malloc).因此,在确定如何传递*this给copy ctor之前,我想知道在使用malloc时如何实例化对象.

man*_*ama 21

placement new获取原始内存后需要使用malloc.

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

当你完成对象时,你必须确保显式调用它的析构函数.

s->~S();
free(mem);
Run Code Online (Sandbox Code Playgroud)


Kit*_*YMG 9

使用新的展示位置

#include <memory>
//...
int main()
{
        S* s = (S*) malloc(sizeof(S));
        s = new (s) S();//placement new
        //...
        s->~S();
        free(s);
}
Run Code Online (Sandbox Code Playgroud)