Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do i need to delete a object that was constructed with new and placement

class Foo{
//some member
    public:
    int bar;
}

int main(){
    char* buffer = new char[100];
    Foo* f = new(buffer)Foo();
//do i have to
    delete f;
//or is 
    delete[] buffer;
//enough
}

Sure i have to delete it if the delete of Foo has some major effect on the system but lets say it is a simple storage object which i place which is compleatly inside of the buffer and has no deconstructor which does delete some other things.

  • Do i have to delete a object which where places with the new inside of a buffer or is it enough to delete the buffer?
  • If i have to call delete on every object inside of the buffer, why do i have todo this?

I read: what-uses-are-there-for-placement-new and he also says

You should not deallocate every object that is using the memory buffer. Instead you should delete[] only the original buffer.

like image 220
BennX Avatar asked Jan 07 '23 21:01

BennX


1 Answers

The correct way to destroy that object is with an explicit destructor call:

f-> ~Foo();

Usually placement new is used with memory on the stack. In this case, it's heap allocation, so you do need to free the buffer using the form of delete that matches the new.

delete[] buffer;
like image 66
Potatoswatter Avatar answered Jan 10 '23 12:01

Potatoswatter