Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete pointer and object

Tags:

c++

How do I delete a pointer and the object it's pointing to?

Will the code below delete the object?

Object *apple;
apple = new Object();

delete apple;

And what happens if the pointer is not deleted, and gets out of scope?

Object *apple;
apple = new Object();

This might be a very basic question, but I'm coming from Java.

like image 430
KaareZ Avatar asked Nov 19 '15 13:11

KaareZ


People also ask

Does deleting a pointer delete the object?

Pointer to object is not destroyed, value or memory block pointed by pointer is destroyed.

Can you delete an object in C++?

When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.

What happens to a pointer when you delete it?

The address of the pointer does not change after you perform delete on it. The space allocated to the pointer variable itself remains in place until your program releases it (which it might never do, e.g. when the pointer is in the static storage area).

Can I use a pointer after delete?

Yes, it's totally fine to reuse a pointer to store a new memory address after deleting the previous memory it pointed to.


1 Answers

Your first code snippet does indeed delete the object. The pointer itself is a local variable allocated on the stack. It will be deallocated as soon as it goes out of scope.

That brings up the second point--if the pointer goes out of scope before you deallocate the object you allocated on the heap, you will never be able to deallocate it, and will have a memory leak.

Hope this helps.

like image 147
Steve Cobb Avatar answered Sep 23 '22 01:09

Steve Cobb