Home > Blockchain >  malloc on struct containing unique_ptr
malloc on struct containing unique_ptr

Time:12-21

Let's say I have the following structure:

struct MyStruct {
    int myInt;
    std::unique_ptr<Something> myUniquePtr;
}

What's wrong when malloc() is used to allocate memory (compared to using new I understand the unique_ptr constructor is not called). What does happen to myUniquePtr?

Let's say just after malloc I perform:

myUniquePtr = std::make_unique<Something>(...)

Is myUniquePtr a valid object?

What could be the consequences?

CodePudding user response:

unique_ptr is a class type. malloc() only allocates raw memory, it does not call any class constructors within that memory. Thus, myUniquePtr will not be initialized correctly, and so cannot be used for anything meaningful since it is not a valid object. It can't be read from. It can't be assigned to. Nothing.

If you use malloc() (or any other non-C allocator) to allocate memory for an object, you must use placement-new afterwards to ensure the object is actually initialized properly in that memory before you can then use the object, eg:

void *memory = malloc(sizeof(MyStruct));
MyStruct *pMyStruct = new(memory) MyStruct;
...
pMyStruct->~MyStruct();
free(memory);
  • Related