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

I read here , as well as elsewhere, that deleting the same variable twice can be catastrophic (even if there is more than one variable name).

Suppose I have a function that accepts an input and output array:

void test(int*& input, int*& output) { if(input[0] == 0) { output = input; } } 

and it can assign a pointer to another variable that I use:

 int *input = new int[3]; int *output = new int[3]; input[0] = 0; test(input, output); delete[] input; delete[] output; 

How can I avoid double deletion?

In this oversimplified scenario, I know that I can check the addresses of pointers to make sure they are equal and conditionally delete only one of them, but is there a better solution when I don’t know that pointers can point to the same memory?

Edit:

tidied up everything to avoid confusion.

+4
source share
2 answers

Generally speaking, the best way to avoid double deletion is to not allocate memory directly with new . There are various smart pointers that can be used as scoped_ptr and shared_ptr , and in your case you can use std::Vector :

 typedef std::vector<int> Ints; void test(const Ints& input, Ints& output) { if(input[0] == 0) { output = input; } } Ints input(3); Ints output(3); input[0] = 0; test(input, output); 
+6
source

To avoid double deletions, you need to create your own code so that ownership of objects is correctly defined. Only one owner of an object can be at a time, although ownership can be transferred from one owner to another. The owner of the object can be part of the code (for example, a function) or a data structure. When the owner is done with the object, the owner must either transfer the property to another, or destroy the object.

+7
source

All Articles