简体   繁体   English

如何避免在c ++中双重删除变量?

[英]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 . 一般来说,避免双重删除的最佳方法是不直接用new分配内存。 There are various smart pointers you can use like scoped_ptr and shared_ptr , and in your case you can use std::Vector : 您可以使用各种智能指针,如scoped_ptrshared_ptr ,在您的情况下,您可以使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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