我有一個帶有向量的程式。該向量采用指向我在程式中動態創建的物件的指標。然后我希望從向量中洗掉這些動態物件。例如:
int main()
{
vector<Account*> allAccounts;
auto timeDone = chrono::system_clock::now();
time_t transactionTime = chrono::system_clock::to_time_t(timeDone);
Account* a1 = new Savings(0, "Savings");
Account* a2 = new Current(0, "Current");
allAccounts.push_back(a1);
allAccounts.push_back(a2);
Transaction* initialTransaction = new Transaction("Initial Deposit", transactionTime, balanceAnswer);
allAccounts[0]->addTransaction(initialTransaction);
allAccounts[1]->addTransaction(initialTransaction);
for (int i = 0; i < allAccounts.size(); i )
{
delete allAccounts[i]; //deletes all dynamically created accounts
}
}
我認為這樣做很好,但是我開始懷疑這是否正確洗掉了向量中的指標。但是我cout << allAccounts.size()在洗掉后使用了 a ,它仍然給出了大小,2就好像帳戶指標仍在向量中一樣。
這是注定要發生的嗎?
另一個注意事項是該Account物件還有一個動態指標向量,這些指標從函式 ( allAccounts[i]->addObject(object)) 中的main 傳遞,然后這些物件以相同的方式在解構式中洗掉。這也是有效的做法嗎?為了消除我的擔憂,這就是我所做的:
float balance;
string accountType
private vector <Transaction*> history;
Account::Account(float b, string a)
{
balance = b;
accountType = a;
}
void Account::addTransaction(Transaction* t)
{
history.push_back(t);
}
Account::~Account()
{
for (int i = 0; i < history.size(); i )
{
delete history[i];
}
history.clear();
}
uj5u.com熱心網友回復:
你在做什么很好(假設Account有一個virtual解構式)并且沒有記憶體泄漏。vector洗掉存盤在其中的指標不會影響的大小。
解構式必須virtual不會導致您的程式具有未定義的行為。
不過,我建議存盤一個像std::unique_ptr<Account>in 中的智能指標vector。當 . 被銷毀時,這將使存盤的物件自動vector銷毀。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/394531.html
下一篇:C中的指標練習
