Reputation: 2134
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..
Upvotes: 4
Views: 1726
Reputation: 340366
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.
Upvotes: 7
Reputation: 96291
Generally speaking the best way to avoid double delete is to not allocate memory directly with new
. There are various smart pointers you can use like 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);
Upvotes: 6