I have a program that has a vector. The vector takes pointers to an object which I dynamically create in my program. I then wish to delete these dynamic objects from the vector. For example:
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
}
}
I believed this was fine to do, however I'm starting to wonder if this does correctly delete the pointers in the vector. However I used a cout << allAccounts.size()
after the delete and it still gives the size as 2
as if the account pointers were still in the vector.
Is this meant to happen?
Another note is that the Account
object also has a vector of dynamic pointers that get passed from main in a function (allAccounts[i]->addObject(object)
) and then these objects get deleted in a destructor in the same way. Is this also a valid thing to do?
Just so I get my worries out the way, this is what I do in account:
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();
}
CodePudding user response:
What you are doing is fine (assuming Account
has a virtual
destructor) and there is no memory leak. The size of the vector
is not affected by deleting the pointers you store in it.
The destructor needs to be virtual
to not cause your program to have undefined behavior.
I would recommend storing a smart pointer like std::unique_ptr<Account>
in the vector
instead though. That would make the destruction of the stored objects automatic when the vector
.is destroyed.