c++ - deleting object pointer referring by two pointers -


i have object say.

classa *obj1 = new classa;  classa *ptr1 = obj1; classa *ptr2 = obj1; 

when delete ptr1;, affect ptr2? if can correct solution this?

(assuming obj2 supposed obj1)

classa *x defines pointer can point objects of type classa. pointer isn't object itself.

new classa allocates (and constructs) actual object of type classa.

so line class *obj1 = new classa; defines pointer obj1 , sets point newly allocated object of type classa.

the line class *ptr1 = obj1; defines pointer ptr1 , sets point same thing obj1 pointing to, is, classa object created.

after line class *ptr2 = obj1;, have 3 pointers (obj1, ptr1, ptr2) pointing same object.

if delete ptr1; (or equivalently, delete obj1; or delete ptr2;), destroy pointed object. after doing this, pointer pointing object made invalid (which answers first question: yes, affect ptr2 in sense ptr2 won't pointing valid object afterwards).

the correct solution depends on you're trying achieve:

  • if want 2 copies of object, assuming classa has copy constructor, classa *ptr2 = new classa(*obj1);. need delete new object separately when done it!
  • if want 2 pointers same object, consider using boost::shared_ptr (google it)

hmm, that's alot of text such simple q+a. ah well.


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -