Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointers - duplicate object instance

Tags:

c++

pointers

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.

like image 890
tambalolo Avatar asked Dec 27 '12 05:12

tambalolo


1 Answers

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.

like image 89
Karthik T Avatar answered Sep 17 '22 16:09

Karthik T