【发布时间】:2021-09-26 12:13:09
【问题描述】:
#include <iostream>
#include<list>
using namespace std;
template <class T>
class Ptr {
public:
Ptr() {
a = nullptr;
l.push_back(0);
}
std::list<int> l;
void print_this() {
cout<<this<<endl;
}
protected:
int *a;
};
int main()
{
Ptr<int> *ptr = new Ptr<int>();
delete ptr;
//ptr = nullptr; //if uncomment this line will crash
auto p = &(ptr->l);
cout<<"p is "<<p<<endl;
ptr->print_this();
ptr->l.push_back(1);
cout<<"size is "<<ptr->l.size()<<endl;
cout<<"end";
return 0;
}
我在这里运行代码:https://www.programiz.com/cpp-programming/online-compiler/ 输出是:
p is 0x5628eb47deb0
0x5628eb47deb0
size is 2
end
如果我在删除后将 ptr 设置为 nullptr,它将在 push_back 处崩溃。但是当我访问列表时仍然可以。
我怎么可能将数据推送到一个悬空指针而不使其崩溃??
【问题讨论】:
-
未定义的行为是未定义的。仅仅因为它看似做了某事并不意味着它是正确的。
-
取消引用无效指针会导致未定义的行为。有时它会让你崩溃,有时会让你的猫活着,如果你真的很不幸,什么都不会发生。您永远无法事先知道它会是哪种替代方案。
-
@Someprogrammerdude 好像我表哥朋友的电脑曾经在拒绝悬空指针后爆炸
-
delete一个对象后,您将无法访问该对象。您访问了该对象。在我的机器上,你的程序崩溃了。 耸耸肩这对你来说是未定义的行为。 -
@m7913d 是的,尤其是这个:运行时库并不总是立即将内存交还给操作系统 :)