一个对象的两个指针.删除了一个指针,对象仍然存在

Two pointers for one object. Deleted one pointer, the object is still there

本文关键字:指针 对象 存在 一个 删除 两个 一个对象      更新时间:2023-10-16

class sphere {
int radius;
public:
sphere(int r){
radius = r;
}
void setRadius(int r) {
radius = r;
}
int getRadius() {
return radius;
}
};
int main()
{
sphere *a, *b;
a = new sphere(1);
b = a;
delete b;
cout << a->getRadius() << endl;
return 0;
}

此代码实际上在控制台上打印出1。根据这篇文章,半径为 1 的球体应该被删除。

我的问题是:

为什么它不返回 SegFault?我期待一个SegFault,因为由于球体被删除,->getRadius将不再可用于a

因为C++标准不需要执行SegFault。这只是未定义的行为,这取决于您的编译器,甚至月相的环境