boom
boom

Reputation: 6156

deleting object pointer referring by two pointers

I have an object say.

ClassA *obj1 = new ClassA;

ClassA *ptr1 = obj1;
ClassA *ptr2 = obj1;

When I do delete ptr1;, will it affect ptr2? If so what can be the correct solution for this?

Upvotes: 0

Views: 537

Answers (2)

dave
dave

Reputation: 13270

(assuming obj2 is supposed to be obj1)

ClassA *x defines a pointer that can point to objects of type ClassA. A pointer isn't an object itself.

new ClassA allocates (and constructs) an actual object of type ClassA.

So the line Class A *obj1 = new ClassA; defines a pointer obj1 and then sets it to point to a newly allocated object of type ClassA.

The line Class A *ptr1 = obj1; defines a pointer ptr1 and then sets it to point to the same thing obj1 is pointing to, that is, the ClassA object we just created.

After the line Class A *ptr2 = obj1;, we have three pointers (obj1, ptr1, ptr2) all pointing to the same object.

If we do delete ptr1; (or equivalently, delete obj1; or delete ptr2;), we destroy the pointed to object. After doing this, any pointer that was pointing to the object is made invalid (which answers your first question: yes, it will affect ptr2 in the sense that ptr2 won't be pointing to a valid object afterwards).

The correct solution depends on what you're trying to achieve:

  • If you want two copies of the object, assuming ClassA has a copy constructor, do ClassA *ptr2 = new ClassA(*obj1);. You will need to delete this new object separately when you are done with it!
  • If you want two pointers to the same object, consider using something like boost::shared_ptr (google it)

Hmm, that's alot of text for such a simple q+a. Ah well.

Upvotes: 2

Daniel Bingham
Daniel Bingham

Reputation: 12914

Assuming obj2 is supposed to be obj1 then yes, calling delete on ptr1 will leave ptr2 with invalid data. The solution to this would be to set ptr1 to NULL if you want to empty it with out losing the object pointed to in ptr2.

Delete is just for when you want to completely free the memory. If you still want to retain the object and data pointed to, but want to clear the pointer, set it to NULL (or (void *) 0).

Upvotes: 1

Related Questions