指向对象的内存位置的指针已在程序中删除,但仍提供正确答案而不是垃圾值

The pointer to memory location to the object has been deleted in program but still provides the correct answer and not garbage value

本文关键字:答案 位置 指针 内存 对象 删除 程序      更新时间:2023-10-16

指针 *sbi 内存是使用 delete 运算符释放的,但代码仍然正确执行而不提供垃圾值。 是构造函数重新初始化还是代码错误/

#include <iostream>
using namespace std;
class bank
{
private:
    int balance;
public:
    bank();
    void dep(int x);
    void with();
    ~bank();
};
int main()
{
    bank *sbi;
    sbi = new bank;
    sbi->dep(50000);
    delete sbi;   /// problem is in this section of code 
    sbi->with();
    return 0;
}
bank :: bank()
{
    balance=0;
}
void bank::dep(int x)
{
    balance=x;
}
void bank::with()
{
    cout<<balance<<endl;
}
bank::~bank()
{
    cout<<"destroy"<<endl;
}

释放内存位置不会自动用垃圾覆盖它。巧合的是,余额中存储的值仍然相同。