sna*_*pop 4 c++ memory-management delete-operator
我在这里以及其他地方已经阅读过两次删除相同的变量可能是灾难性的(即使有多个变量名称).
假设我有一个带输入和输出数组的函数:
void test(int*& input, int*& output) {
if(input[0] == 0) {
output = input;
}
}
Run Code Online (Sandbox Code Playgroud)
它可以指定一个指向另一个我正在使用的变量的指针:
int *input = new int[3];
int *output = new int[3];
input[0] = 0;
test(input, output);
delete[] input;
delete[] output;
Run Code Online (Sandbox Code Playgroud)
我怎样才能避免双重删除?
在这个过于简化的场景中,我知道我可以检查指针地址以查看它们是否相等并且有条件地仅删除其中一个,但是当我不知道指针可能指向同一个内存时,是否有更好的解决方案?
编辑:
收拾东西以避免一些混乱..
避免双重删除的方法是设计代码,以便很好地定义对象的所有权.尽管所有权可以从一个拥有实体传递到另一个拥有实体,但一次只能有一个对象的所有者.对象所有者可以是一段代码(例如函数)或数据结构.当所有者完成一个对象时,所有者有责任将所有权传递给其他东西或销毁该对象.
一般来说,避免双重删除的最佳方法是不直接分配内存new
.有各种不同的智能指针,你可以使用像scoped_ptr
和shared_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);
Run Code Online (Sandbox Code Playgroud)