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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With