Using malloc instead of new, and calling the copy constructor when the object is created

半城伤御伤魂 提交于 2019-12-01 06:44:28

You'll need to use placement new after getting the raw memory from malloc.

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

When you're done with the object you have to make sure to explicitly call its destructor.

s->~S();
free(mem);
KitsuneYMG

Use placement new

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

The parameter to allocate() is the number of objects, not the size in bytes. You then call the allocator's construct() function to construct the object.

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

If want to use it with a standard library container or other std allocator aware type, simply give it the allocator type.

std::vector<SomeClass, scalable_allocator<SomeClass>> v;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!