How to call a constructor on an already allocated memory?

后端 未结 3 658
甜味超标
甜味超标 2020-12-16 10:16

How can I call a constructor on a memory region that is already allocated?

3条回答
  •  忘掉有多难
    2020-12-16 10:18

    The placement new constructor mentioned by the accepted answer is an old way before the allocator class defined in header. Now you really should do(in C++11 style):

    allocator alloc;
    //Allocate memory for one or n objects
    auto p = alloc.allocate(1); 
    //Construct an object of Foo on allocated memory block p, by calling one of Foo's constructors
    alloc.construct(p, args, ...); 
    
    //OK, p now points to a Foo object ready for use...
    
    //Call Foo's destructor but don't release memory of p
    alloc.destroy(p); 
    //Release memory
    alloc.deallocate(p, 1); 
    

    That's it.

提交回复
热议问题