13

If I have

Class *a1 = new Class();
Class *b1 = a1;

delete b1;
delete a1; //this will give a double free or corruption message;

if I delete pointer b, it's the same as deleting pointer a right? Since the two are pointing at the same instance of Class. So, how can I copy the instance of a1 to b1 so that when I delete b1, a1 is NOT deleted.

Class *a1 = new Class();
Class *b1 = a1;

//how do I duplicate the instance a1 is pointing
//so that when I delete b1, a1 still exists.

delete b1; 
delete a1; //this is still valid 

Thanks.

tambalolo
  • 1,035
  • 3
  • 14
  • 30
  • 1
    Not sure about all of the pointers being necessary, but `Class *b1 = new Class(*a1);` should do it. – chris Dec 27 '12 at 05:58
  • Make sure your copy constructor is OK and create a new copy from *a1. – halfelf Dec 27 '12 at 06:01
  • That was easy @.@ Thanks – tambalolo Dec 27 '12 at 06:04
  • @markuz, Yeah, if you use `new` at all *in* your class, that won't cut it without the Rule of 3/5. Take a look at these: [first](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) [second](http://dl.dropbox.com/u/6101039/Modern%20C++.pdf) – chris Dec 27 '12 at 06:09

1 Answers1

15

Is there a reason you are using pointers and allocation? Else its as simple as

Class a1;
...
Class b1 = a1;

There is no need here for a delete.

If you need to keep the structure as it is you need to do

Class *a1 = new Class();
Class *b1 = new Class(*a1);

or

Class *a1 = new Class();
Class *b1 = new Class();
*b1 = *a1;

This assumes you have a valid copy-constructor ( e.g #1) or assignment operator (e.g #2)

p.s: try to use std::unique_ptr instead of raw pointers to be safer.

Karthik T
  • 31,456
  • 5
  • 68
  • 87
  • 4
    What if somebody else wrote Class and they did not add copy-constructor or assignment operator? – corro Aug 12 '15 at 18:23
  • @corro the default copy constructor is shallow copy(`memcpy`), but it failes if the Classes have Pointers or some other resources inside, therefore it is to be used with care. furthermore, it is encouraged that if you aint going to implement a copy/assignment you should implement a private empty one to prevent anyone of using the default shallow copy – Tomer W Feb 19 '19 at 06:05