How to call a constructor on an already allocated memory?

后端 未结 3 652
甜味超标
甜味超标 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<Foo> 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.

    0 讨论(0)
  • 2020-12-16 10:19

    Notice that before invoking placement new, you need to call the destructor on the memory – at least if the object either has a nontrivial destructor or contains members which have.

    For an object pointer obj of class Foo the destructor can explicitly be called as follows:

    obj->~Foo();
    
    0 讨论(0)
  • 2020-12-16 10:21

    You can use the placement new constructor, which takes an address.

    Foo* foo = new (your_memory_address_here) Foo ();
    

    Take a look at a more detailed explanation at the C++ FAQ lite or the MSDN. The only thing you need to make sure that the memory is properly aligned (malloc is supposed to return memory that is properly aligned for anything, but beware of things like SSE which may need alignment to 16 bytes boundaries or so).

    0 讨论(0)
提交回复
热议问题