Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

destructors of array placement new

I haven't been able to find an answer for this :

T * blockPtr = static_cast<T*>(malloc(nb*sizeof(T)));
new (blockPtr) T[nb];
// use my blockPtr array
// call destructors (?)
free(blockPtr);

In that case, what is the correct way to call destructors ? Should I manually loop on every item and call every destructor or is there a specific syntax to do this in one call ? I know that when calling delete[] on a class T, some compilers like MSVC usually have behind the scene a specific "vector destructor" to do this.

like image 894
lezebulon Avatar asked Sep 20 '25 09:09

lezebulon


2 Answers

Should I manually loop on every item and call every destructor

Yes.

is there a specific syntax to do this in one call ?

No.


I hope you really need to do this!

like image 177
Lightness Races in Orbit Avatar answered Sep 22 '25 22:09

Lightness Races in Orbit


When using placement-new, you have to call the destructors yourself:

void * blockPtr = malloc(nb*sizeof(T));
T * block = new (blockPtr) T[nb];

// use block array ...

// call destructors
for (int i = 0; i < nb; ++i)
    block[i].~T();

free(blockPtr);
like image 37
Remy Lebeau Avatar answered Sep 23 '25 00:09

Remy Lebeau