【发布时间】:2026-02-12 09:55:01
【问题描述】:
我有某种内存泄漏问题。我在前面的几行中有它,但我通过编写一个复制赋值构造函数来纠正它。但问题出在delete newB 行。当我注释掉该行时,会弹出另一个错误。你认为我在哪里有一些内存泄漏,因为我知道它与内存分配有某种关系。
void BankingSystem::addBranch(const int id, const string name){
if(isBranchExisting(id)){
cout << "\n\tBranch " << id << " already exists. Please try it with another id number.";
}
else if(!isBranchExisting(id)){
Branch* tempArray = new Branch[cntBranches];
if(cntBranches != 0){
for(int i = 0; i<cntBranches; i++){
tempArray[i] = allBranches[i];
}
delete[] allBranches;
allBranches = new Branch[cntBranches+1];
for(int i = 0; i<cntBranches; i++){
allBranches[i] = tempArray[i];
}
allBranches[cntBranches] = Branch(id, name);
delete[] tempArray;
}
Branch* newB = new Branch(id,name);
allBranches[cntBranches] = *newB;
cout << "\n\tBranch " << id << " is added successfully.";
delete newB;
cntBranches++;
}
}
如果您需要,我也可以向您展示 Branch 类,因为它也可能与构造函数或析构函数有关,但我未能成功纠正这些错误,因为此错误继续弹出。
编辑:对不起,我以为我说了。
【问题讨论】:
标签: c++ memory-management heap-memory destructor