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

后端 未结 3 1359
眼角桃花
眼角桃花 2021-01-13 18:56

I wanted to try out TBB\'s scalable_allocator, but was confused when I had to replace some of my code. This is how allocation is done with the allocator:

Som         


        
相关标签:
3条回答
  • 2021-01-13 19:52

    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;
    
    0 讨论(0)
  • 2021-01-13 19:55

    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);
    
    0 讨论(0)
  • 2021-01-13 19:58

    Use placement new

    #include <memory>
    //...
    int main()
    {
            S* s = (S*) malloc(sizeof(S));
            s = new (s) S();//placement new
            //...
            s->~S();
            free(s);
    }
    
    0 讨论(0)
提交回复
热议问题