how to destroy an object in C++

delete &b;

You may not do that. delete must only be used on pointers returned from allocating non-array new. You did not get &b from an allocating new-expression.


You could approach the problem from another direction: Since the number of objects doesn’t change, it could be much simpler to think of the state of the object changing, instead of destroying and creating a new one. You could simply write a member function that resets the state of the object as desired:

if(b.collision) {
     b.reset_state();
}

That said, it is technically possible to destroy an automatic (or static) variable as long as you create a new one in its place (as is your intention).

The destruction is done by invoking the destructor, while the construction is done using a placement-new expression:

b.~line();
new(&b) line;

But this approach has more caveats than keeping the single object throughout.

Leave a Comment