deleting object pointer referring by two pointers

纵饮孤独 提交于 2020-01-06 19:55:10

问题


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:


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




回答2:


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



来源:https://stackoverflow.com/questions/3775427/deleting-object-pointer-referring-by-two-pointers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!