Assuming MyClass uses the default destructor (or no destructor), and this code:
MyClass *buffer = new MyClass[i];
// Construct N objects using placement new
for(size_t i = 0; i < N; i++){
buffer[i].~MyClass();
}
delete[] buffer;
Is there any optimizer that would be able to remove this loop?
Also, is there any way for my code to detect if MyClass is using an empty/default constructor?
EDIT: Sorry about my horrible code. I think this is correct now..
There are a few things wrong with this code.
Firstly, you don’t need to be calling the destructor.
MyClass buffer* = new MyClass[i]; delete[] buffer;does that just fine. (Note, not the array syntax.)That said, you comment leads me to believe you meant something else, like:
Then later:
Of course there’s no need to delete anything, since we used a vector. This is the correct syntax for calling a destructor.
Will it be optimized? It depends of the compiler can determine if the destructor does nothing. If the destructor is compiler-generated, I’m sure it’ll remove the worthless loop. If the destructor is user-defined but in the header, it’ll also be able to see it does nothing and remove the loop.
However, if it’s in some other object file, I don’t think it will, even if it’s empty. That depends on your compilers ability to optimize during the linking phase. The best way to know is to look at the generated assembly.