Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deleting array elements constructed with placement new

I was looking into the case when we create a dynamic array of class types. As I know there isn't a method to create the array while calling a non-default constructor of the class directly. One way to so is initializing the array with normally and then looping and calling the non-default constructor for each object, but I think there is significant overhead in that approach. After looking for a solution, I found the following using the placement new:

void* memory = operator new[](sizeof(Test) * 8);  // Allocate raw memory for 8 objects
Test* arr = static_cast<Test*>(memory);  //Convert to desired type
// Construct objects using placement new

for (int i = 0; i < 8; i++) {
    new (&arr[i]) Test(9);  //Assume Test has constructor Test(int)
}

// Use the initialized array

for (int i = 0; i < 8; i++) {
    arr[i].~test();  // Explicitly call destructor for each object
}
operator delete[](memory);  // Deallocate memory

I am wondering if it is possible to deallocate the memory as the following:

delete[] arr;
/*instead of 
for (int i = 0; i < 8; i++) {
    arr[i].~test();
}
operator delete[](memory); */

I tested it in VS2022 but I want to make sure that there aren't problems with the approach.

In VS debugger the code was running without problems, but I am worried about possible memory leaks or deleting more than what's already allocated.

like image 909
Yousef Irshaid Avatar asked Nov 29 '25 17:11

Yousef Irshaid


1 Answers

I am wondering if it is possible to deallocate the memory as the following:

delete[] arr;

The answer is no.

To be able to use the delete[] operator you must have allocated and initialized it with the new[] operator.

Match delete with new, and delete[] with new[]. If you do an explicit call to the operator new or operator new[] functions, you must use the corresponding delete function. Anything else leads to undefined behavior.

like image 119
Some programmer dude Avatar answered Dec 02 '25 07:12

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!