在c++中,Delete指针和重新分配给出了相同的结果

delete pointers and reallocation are giving same result in c++?

本文关键字:分配 结果 c++ Delete 指针 新分配      更新时间:2023-10-16

我有c++指针删除和重新分配的问题。请给我讲讲这两种方法。我没有机会使用智能指针。(这不是一个实际的代码-我应该用int代替引用类型)

#include <iostream>
#include <queue>
using namespace std;
int main() {
    queue<int*>q;
    int* a= new int(5);
    q.push(a);
   /* 1. method */
    while (!q.empty()) {
        int* x = q.pop();
        ....do something...
        delete x;/* is here deleting the firstly created int a object? */
       /* or only deleting newly created allocation of *x? */
    }
    /* 2. method */
    int* x = q.pop();
    while (!q.empty()) {        
        ....do something...
        *x = q.pop();
    }
    /* here i'm reallocating the values for x. is here deleting firstly created  int a object? */
    /* is 2 method = 1 method ? */

    return 0;
}

delete x;/* is here deleting the firstly created int a object? */

是的。new调用分配内存并返回一个指针,您将其压入队列。然后(尝试)将值弹出到x中。你可以随心所欲地复制指针,但是它们只会被分配和删除一次。

/* or only deleting newly created allocation of *x? */

什么?不。不管你想问什么,答案都是否定的。这个问题很麻烦。

/* here i'm reallocating the values for x. is here deleting firstly created int a object? */

不,你不是在"重新分配x的值"。假设这段代码可以编译(实际上没有),但假设它做了您认为它应该做的事情,那么答案是否定的。你也不能删除"首次创建为一个对象"

发生的情况是,您泄漏了存储在a中的原始值的内存(随后推入队列),因为您从未删除它。此外,第一次弹出后队列为空,您永远不会进入循环。

但是如果确实进入循环,则会出现类型冲突,此时您将刚刚弹出的指针存储到您最初在a中分配的整数大小的内存位置,并弹出到x中。你的编译器应该警告你。

现在让我们假设你说(这里我也向你展示从std::queue访问和弹出的正确方法):

x = q.front();
q.pop();

现在您仍然泄漏了x的旧值,因为您没有将其存储在其他地方并且没有删除它。你已经用队列中的下一个值替换了它,你也没有删除它,所以你也可能会泄漏。

/* is 2 method = 1 method ? */

。方法一是最正确的,但是你还是错了。你的意思:

while( !q.empty() )
{
    int *x = q.front();
    q.pop();
    // do something...
    delete x;
}