在我调用delete,c ++之后仍然可以访问值

use*_*774 1 c++ memory heap pointers

我有类,一个Employee类和一个BankAccount类,employee类将BankAccount类作为私有变量指针.

这就是我想要做的:

  1. 我需要BankAccount在每个Employee值中设置所有s
  2. 然后,我删除所有BankAccounts每一个Employee在函数结束.

我使用成员函数setter Employee来设置BankAccount指针.BankAccount有一个私有变量,这是金额.后来我在一个指向每个BankAccount's内存地址的指针上调用delete .在我打电话给印刷品以查看每个银行的银行值之后Employee,它仍然是每个的打印值BankAccount

如果我调用delete不应该删除堆上的内存并且调用print时不输出任何内容BankAccount

这是代码:

vector<Employee*> employees;

//get employee full name & salary and return
employees.push_back(get_employee_info());

//setup their bank account
setup_bank(employees);

//make temp pointer to store bank memory address
BankAccount * tempBankPtr;

for (int i =0; i < employees.size(); i++) {
    tempBankPtr =employees[i]->get_bank();
    delete tempBankPtr // delete the heap object that pointer is pointing at
}

//print values
for (int i =0; i< employees.size(); i++) {
    employees[i]->print();
}
Run Code Online (Sandbox Code Playgroud)

打印代码

void Employee:: print() const {

    cout << "First name is: " << firstName << "\n";
    cout << "Last name is: " << lastName << "\n";
    BankAccount* bankholder = NULL;
    bankholder = get_bank();
    if(bankholder != NULL)
    cout << "Account Balance is: " << get_bank()->get_amount() << "\n"; //prints values
}
Run Code Online (Sandbox Code Playgroud)

银行吸气剂

BankAccount* Employee::get_bank() const{
    return bank;
}
Run Code Online (Sandbox Code Playgroud)

这在setup_bank中调用

void Employee::set_bank(Employee* e, double amount){
       bank = new BankAccount(amount);
}
Run Code Online (Sandbox Code Playgroud)

Lig*_*ica 10

如果我调用delete不应该删除堆上的内存,并且当调用print时不为BankAccount输出任何东西?

没有.

删除内存中该位置的对象意味着它不再存在,因此不允许您访问它.

这并不意味着你的程序会神奇地打印"虚无"以保护你免受这个错误的影响.

因此,您的程序具有未定义的行为 ; 必须确保你没有取消引用无效指针!


归档时间:

查看次数:

696 次

最近记录:

9 年,9 月 前