0

Instead of:

MyClass* A = new MyClass[128];
delete[] A;

can I do this:

MyClass* A = new MyClass[128];
for ( int i = 0; i < 128; ++i )
{
    delete &A[i];
}

expecting that the memory pointed to by A will be deallocated and every element's destructor called properly?

Coder
  • 9
  • 1
  • 1
    Each destructor is already called in the first *valid* version. So why are wishing to loop yourself? – StoryTeller - Unslander Monica Apr 10 '22 at 14:04
  • 3
    `A[i]` isn't a pointer. – YSC Apr 10 '22 at 14:04
  • @YSC pardon me. I have corrected it. Can you answer now? The suggested question is not the same as my question. – Coder Apr 10 '22 at 14:36
  • You cannot do that. You can call `delete` on pointers to objects you allocated with `new` (or on null pointers). So you can't `delete &A[i]`: it's _undefined behavior_. You may manually call the destructors like this: `A[i].~MyClass()` but, still, I don't get why you'd do it. You would then still have to decide between calling `delete[] A` (achieving again _UB_, as the destructor would be called again on each element) or a memory leak (i.e. not calling `delete A[]`). – paolo Apr 10 '22 at 15:56
  • But calling `delete A` and then `A[i].~MyClass()` would do what `delete[] A` does right? I just want to know if `delete[]` does exactly that; ie if I could replicate it like that. Thank you very much. – Coder Apr 10 '22 at 16:56
  • @Coder calling `delete`/`delete[]` on memory not allocated with `new`/`new[]` (respectively), or manually calling destructors on memory not allocated with `placement-new`, is *undefined behavior* - period. Just don't do it. You can't replicate what `delete[]` does, because you don't have access to the same internals that the compiler/runtime has access to. – Remy Lebeau Apr 10 '22 at 18:26

0 Answers0