在我调用Delete之后,值仍然可以访问,C ++ [英] Values still accessible after I call delete, c++

查看:164
本文介绍了在我调用Delete之后,值仍然可以访问,C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须要上一个类,一个Employee类和一个BankAccount类,雇员类具有BankAccount类作为私有变量指针.

I have to classes, one Employee class and one BankAccount class, the employee class has the BankAccount class as a private variable pointer.

这就是我想要做的:

  1. 我需要为每个Employee中的所有BankAccount设置值
  2. 然后在函数末尾删除每个Employee的所有BankAccounts.
  1. I need to set up all the BankAccounts in each Employee with values
  2. then I delete all BankAccounts for every Employee at the end of the function.

我在Employee中使用成员函数设置器来设置BankAccount指针. BankAccount有一个私有变量,即数量.稍后,我在指向每个BankAccount's内存地址的指针上调用delete.在我调用print来查看每个Employee的库的值之后,它仍在为每个BankAccount

I use a member function setter in Employee to set up the BankAccount pointer. BankAccount has one private variable and that is amount. Later I call delete on a pointer that should point to each BankAccount's memory address. After I call print to see the values of the bank for each Employee and it is still printing values for each BankAccount

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

If I call delete shouldn't the memory on heap be delete and when print is called not output anything for 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();
}

打印代码

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
}

获取银行

BankAccount* Employee::get_bank() const{
    return bank;
}

这在setup_bank中被称为

this is called in setup_bank

void Employee::set_bank(Employee* e, double amount){
       bank = new BankAccount(amount);
}

推荐答案

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

If I call delete shouldn't the memory on heap be delete and when print is called not output anything for BankAccount?

否.

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

Deleting the object at that location in memory means it does not exist any more, so you're not allowed to access it.

这并不意味着您的程序将神奇地打印虚无"以保护您免受此错误的侵害.

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

Your program therefore has undefined behaviour; you must make sure you do not dereference an invalid pointer!

这篇关于在我调用Delete之后,值仍然可以访问,C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆