Aviv Cohn
Aviv Cohn

Reputation: 17183

Does `delete <pointer>` destroy only the pointer, or also the pointee?

In C++ we always have to delete a pointer after we newed it.

But I'm trying to understand if that simply deletes the pointer, or also calls the destructor of the pointed to object.

For example:

Thing* pointer = new Thing;
// .. some code
delete pointer;

Does this call the destructor of the object pointed to by pointer? Or does it only destory the pointer?

Upvotes: 2

Views: 1339

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254431

Does this call the destructor of the object referenced by pointer?

Yes, it destroys the object by calling its destructor. It also deallocates the memory that new allocated to store the object.

Or does it only destory the pointer?

It does nothing to the pointer. That still exists, but no longer points to a valid object, so can't be used until you assign a valid pointer value to it.

Upvotes: 6

Related Questions