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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
(assuming
obj2is supposed to beobj1)ClassA *xdefines a pointer that can point to objects of typeClassA. A pointer isn’t an object itself.new ClassAallocates (and constructs) an actual object of typeClassA.So the line
Class A *obj1 = new ClassA;defines a pointerobj1and then sets it to point to a newly allocated object of typeClassA.The line
Class A *ptr1 = obj1;defines a pointerptr1and then sets it to point to the same thingobj1is pointing to, that is, theClassAobject 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;ordelete 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 affectptr2in the sense thatptr2won’t be pointing to a valid object afterwards).The correct solution depends on what you’re trying to achieve:
ClassAhas a copy constructor, doClassA *ptr2 = new ClassA(*obj1);. You will need todeletethis new object separately when you are done with it!boost::shared_ptr(google it)Hmm, that’s alot of text for such a simple q+a. Ah well.