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.
The answer is no.
To be able to use the
delete[]operator you must have allocated and initialized it with thenew[]operator.Match
deletewithnew, anddelete[]withnew[]. If you do an explicit call to theoperator neworoperator new[]functions, you must use the corresponding delete function. Anything else leads to undefined behavior.