简体   繁体   中英

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.

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!

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM