C++:关于vector内数据为堆内申请的指针类型时 对数据delete后的结果疑问


#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<int*> vec;
    int* pa = new int(1);
    int* pb = new int(2);
    int* pc = new int(3);
    vec.push_back(pa);
    vec.push_back(pb);
    vec.push_back(pc);
    for (auto x : vec)
    {
        cout << x << ":" << *x;
        cout << endl;
    }

    //cout << "clear():" << endl;
    //vec.clear();
    //for (auto x : vec)
    //    cout << x << " ";
    //cout << endl;

    cout << "delete\n";
    vector<int*> pvec;
    pvec.push_back(pa);
    pvec.push_back(pb);
    pvec.push_back(pc);
    for (auto x : pvec)
    {
        delete x;
    }
    for (auto x : pvec)
    {
        cout << x << ":" << *x;
        cout << endl;
    }
    return 0;
}

输出结果:
004695F0:1
00469600:2
00499610:3
delete
004695F0:1
00469600:2
00499610:3

请问为什么delete之后地址内的数据还存在

delete后,这部分内存可能还没有被分配给其它变量,指针指向的内存还没有被别的数据覆盖。所以值没有改变。
这时候vector中的指针就是野指针。
所以,在使用vector的时候,如果delete了vector中元素的内存,最好及时把这个元素从vector中删除,或者把指针置为0

int i=0;
for (auto x : pvec)
{
    delete x;
    pvec[i++] = 0; //把删除的指针置0
}

首先,这个和vector没有任何关系,只是运气好而已,那块内存没有被使用。

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632

一个指针被delete之后,这个指针就失效了,就不能对它进行解引用,否则的话,其行为是undefined behavior。何为undefined behavior?就是程序运行状态不可预测,有可能仍然得到正确结果,也有可能得到错误结果,甚至程序崩溃。

https://en.cppreference.com/w/cpp/memory/new/operator_delete

After the standard library deallocation function returns, all pointers referring to any part of the deallocated storage become invalid.

Indirection through a pointer that became invalid in this manner and passing it to a deallocation function (double-delete) is undefined behavior. Any other use is implementation-defined.