How to create an object in dynamic memory using malloc ()? You need to explicitly call the constructor, how to do it?

  • new (ptr) Type (/ * params * /); - Croessmah

1 answer 1

You need placement new.

For example:

void* place = malloc(sizeof(Object)); Object* o = new(place) Object(); 

Do not forget to call the destructor manually at the end:

 o->~Object(); 

and if needed

 free(place); 

Documentation: https://isocpp.org/wiki/faq/dtors#placement-new


For the case when your memory is allocated in advance, you will have to take care of alignment. A regular pointer, which returns malloc , has an alignment sufficient for a normally declared class, that is, a class whose definition does not contain alignas() (and also the definition of the classes of its fields), which means that nothing else needs to be done.

If this (lack of alignas ) is not guaranteed, you have two alignas . You can use aligned_alloc (or _aligned_malloc on older versions of Visual Studio) instead of malloc , which produces a malloc with the necessary alignment:

 void* place = std::aligned_alloc(alignof(Object), sizeof(Object)); void* place = _aligned_malloc(sizeof(Object), alignof(Object)); 

(yes, the opposite order).

Or if you need malloc , then you can order more memory so that there is room for alignment, and align the pointer with std::align :

 std::size_t alloc_size = sizeof(Object) + alignof(Object) - 1; void* place = malloc(alloc_size); void* aligned_place = place; if (std::align(alignof(Object), sizeof(Object), aligned_place, alloc_size)) { Object* o = new(aligned_place) Object(); // ... } 

This second technique is useful if you want to allocate several objects in one buffer.

  • will malloc do the right alignment? - Abyx
  • @Abyx: Well noticed. No, there is no guarantee, of course. Manual align not very comme il faut. However, an example from the C ++ FAQ does the same: - / - VladD
  • five
    It is ok. - from the answer to the question “How does malloc understand alignment?” - ߊߚߤߘ
  • @Arhad: Wow, I didn't know that, thanks. - VladD
  • 2