views:

84

answers:

3

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?

+1  A: 

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).

Daniel Bingham
In C++, `NULL` is just 0 (or equivalent), not a pointer type.
GMan
+2  A: 

(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.

dave
@dave Thnx a lot now got that concept.
iSight
+1  A: 

Having 2 good answers above explaining answer to the problem, you might want to give a look to smart pointers to handle scenarios such as above. Here's the link: http://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one

Reference counted smart pointers is what can be used for the scenario.

Als