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

标签 c++ pointers memory heap-memory

<分区>

我有两个类,一个Employee类和一个BankAccount类,employee类将BankAccount类作为私有(private)变量指针。

这就是我想要做的:

  1. 我需要为每个 Employee 中的所有 BankAccount 设置值
  2. 然后我在函数末尾删除每个 Employee 的所有 BankAccounts

我在 Employee 中使用成员函数 setter 来设置 BankAccount 指针。 BankAccount 有一个私有(private)变量,那就是金额。稍后,我在应该指向每个 BankAccount 的 内存地址的指针上调用 delete。在我调用 print 查看每个 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();
}

打印代码

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
}

银行 setter/getter

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

这在 setup_bank 中调用

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

最佳答案

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

没有。

删除内存中那个位置的对象意味着它不再存在,所以你不能访问它。

It does not mean your program will magically print "nothingness" to protect you from this mistake.

因此你的程序有未定义的行为必须确保您没有解除对无效指针的引用!

关于c++ - 在我调用 delete 之后仍然可以访问值,c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34055639/

相关文章:

c++ - 正确的超时非阻塞套接字事件处理?

c - 生命游戏指针

java - 释放 JavaFX 资源

c# - 你能阻止内存被交换到磁盘吗?

c++ - 编写 C++ 程序压缩/解压缩数据

c++ - 如何在 C++ 中初始化 const int 二维 vector

c++ - 需要一个好的方法来在 Google Test 中测试工厂类

c - 了解指针数组语法

c - 使用指针 c 反转数组

c - 将 argv 给出的内存地址分配给 c 中的指针