use*_*774 1 c++ memory heap pointers
我有类,一个Employee
类和一个BankAccount
类,employee类将BankAccount
类作为私有变量指针.
这就是我想要做的:
BankAccount
在每个Employee
值中设置所有sBankAccounts
每一个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 次 |
最近记录: |