14

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.

5
  • 1
    Not sure about all of the pointers being necessary, but Class *b1 = new Class(*a1); should do it. Commented Dec 27, 2012 at 5:58
  • Make sure your copy constructor is OK and create a new copy from *a1. Commented Dec 27, 2012 at 6:01
  • That was easy @.@ Thanks Commented Dec 27, 2012 at 6: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 second Commented Dec 27, 2012 at 6:09
  • Do you find a solution? For "struct", suggested methods not work. Commented Apr 3, 2024 at 21:09

1 Answer 1

16

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What if somebody else wrote Class and they did not add copy-constructor or assignment operator?
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.