user4194399
user4194399

Reputation:

What will get removed if i remove a pointer in c++

If I remove a pointer to an object, what will be removed? Only the pointer or also the object which the pointer points to? For example:

Assume I have a class with a variable

int *root

If I do the following in a method of that class

int *current = root;
delete current;

Will root also be deleted or only the pointer current?

Upvotes: 2

Views: 229

Answers (4)

Baum mit Augen
Baum mit Augen

Reputation: 50053

I think you have a misconception about what delete does: delete deletes an object pointed to by a pointer that was previously allocated with new:

int* p = new int; // Create a new int and save its address in p
delete p;         // Delete the int

Note that this does not delete p itself in any way, but only the object p points to! You can still use p like a normal variable, e.g. reassign it.

Upvotes: 3

user3920237
user3920237

Reputation:

When you have multiple pointers to a pointee you only need to call delete on one of them.

int* root = new int;
int* current = root;
delete current;
std::cout << *root; // undefined behavior

The behavior of delete is described in §5.3.5:

6 If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will invoke the destructor (if any) for the object or the elements of the array being deleted. In the case of an array, the elements will be destroyed in order of decreasing address (that is, in reverse order of the completion of their constructor; see 12.6.2).

Upvotes: 1

ravi
ravi

Reputation: 10733

int *pointer = new int;

After this statement pointer would be pointing( pointer would be containing the address ) to a block of memory enough to store integer. What internally happens is some chunk from free store would be assigned allocated status.

When you execute

delete pointer;

That memory is returned back to free store so as to fulfill future needs. But you pointer would be containing the same address. When you execute delete again , it would led to undefined behavior since that block is already returned to free store ( that means you have lost the control over that memory through this pointer )

So, to be on safe side you generally set pointer to 0 after deleting that memory.

pointer = NULL;

In implementation of operator delete there is code which check if pointer is NULL, if it is then it returns. So, it's said that there's no harm in deleting NULL pointer.

I hope I have covered every basics.

Upvotes: 0

Caduchon
Caduchon

Reputation: 5191

Yes, root is deleted, but depending of the compiler, current can still contain the address of an unexisting variable. So you have to do this to avoid mistakes :

delete current;
current = 0;

Upvotes: 0

Related Questions