Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid double deleting variables in c++?

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..

like image 818
snapfractalpop Avatar asked Dec 10 '22 21:12

snapfractalpop


1 Answers

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.

like image 73
Michael Burr Avatar answered Dec 13 '22 12:12

Michael Burr