【发布时间】:2016-03-06 10:42:11
【问题描述】:
我有一个我调用的成员函数,从那里我得到一个指向 BankAccount 类的私有成员的指针,我不确定当我解除分配指针时会发生什么。我创建了一个新的指针和堆内存地址,然后将指针分配给其他东西。 “删除”最终会删除什么?
我读到如果你删除一个指针
这里是代码
void Employee::raise(){
BankAccount* tempBank = new BankAccount(); //set pointer to new heap place
double amt;
tempBank = get_bank(); // set pointer to existing heap implicitly
amt = tempBank->get_amount();
amt = (amt + (amt/12));
tempBank->set_amount(amt);
delete tempBank; //does this delete new heap created or does it add a new block of
//memory to heap since it is trying to delete a pointer assigned
//by memory address
tempBank = NULL;
}
我意识到我可以执行下面的代码来避免这种情况,但现在我很好奇在上述情况下内存会发生什么
BankAccount* tempBank = get_bank();
那么在我原来的情况下调用 delete 时究竟会发生什么?
【问题讨论】:
-
顺便说一句,在它消失之前将
tempBank设置为NULL是没有意义的。
标签: c++ pointers memory memory-management heap-memory