I have read here, as well as elsewhere, that deleting the same variable twice can be disastrous (even when there is more than one variable name).
Suppose I have a function which takes an input and output array:
void test(int*& input, int*& output) {
if(input[0] == 0) {
output = input;
}
}
and it may assign a pointer to another variable I'm using:
int *input = new int[3];
int *output = new int[3];
input[0] = 0;
test(input, output);
delete[] input;
delete[] output;
how can I avoid the double delete?
In this overly simplified scenario, I know I could check the pointer addresses to see if they are equal and conditionally only delete one of them, but is there a better solution when I won't know pointers might be pointing to the same memory?
Edit:
tidied up the things to avoid some confusion..
The way to avoid double deletes is to design your code so that the ownership of objects is well defined. There can only be one owner of an object at a time, though ownership can be passed from one owning entity to another. An object owner can be a piece of code (such as a function) or a data structure. When the owner is done with an object, it is the owner's responsibility to either pass ownership to something else or to destroy the object.
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