gpt4 book ai didi

c++ - 删除后访问指针

转载 作者:太空狗 更新时间:2023-10-29 20:33:18 25 4
gpt4 key购买 nike

<分区>

我有如下代码片段。我为我的 Something 类创建了一些动态内存分配,然后删除了它们。代码打印了我期望的错误数据,但为什么 ->show 没有崩溃?在什么情况下/如何 ->show 会导致崩溃?是否可以用其他对象覆盖 i、ii、iii 的相同内存位置?

我试图理解为什么在 delete 释放了要用其他东西写入的内存位置之后仍然有关于 ->show 的信息!

#include <iostream>
#include <vector>

class Something
{
public:

Something(int i) : i(i)
{
std::cout << "+" << i << std::endl;
}

~Something()
{
std::cout << "~" << i << std::endl;
}

void show()
{
std::cout << i << std::endl;
}
private:
int i;

};

int main()
{
std::vector<Something *> somethings;

Something *i = new Something(1);
Something *ii = new Something(2);
Something *iii = new Something(3);

somethings.push_back(i);
somethings.push_back(ii);
somethings.push_back(iii);

delete i;
delete ii;
delete iii;

std::vector<Something *>::iterator n;
for(n = somethings.begin(); n != somethings.end(); ++n)
{
(*n)->show(); // In what case this line would crash?
}

return 0;
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com