简体   繁体   中英

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

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM