user3470131
user3470131

Reputation: 21

Should I delete an array of dereferenced pointers?

I'm not sure if this is good coding practice, so please correct me if I am wrong.

I needed a way to dynamically create a Transaction class and add the object to a vector of Transaction objects. This is what I did:

class Transaction {
    int data;
    Transaction(int d) : data(d) {}
};

class Container {
    std::vector<Transaction> transactions;
    void createTransaction();
};
void Container::createTransaction() {
    int data;
    std::cout << "Enter your data: ";
    std::cin >> data;
    Transaction t = new Transaction(data); 
    // In order to keep the object from destruction at end of function. 
    // Possibly could be done with static as well.
    transactions.push_back(*t);
}

The vector is a vector of objects, not pointers. Is this a case where I do not need to delete the dynamic memory, as it will delete itself upon the end of the program/scope?

Is this a terrible way to go about creating objects dynamically and storing them?

Upvotes: 0

Views: 112

Answers (2)

quantdev
quantdev

Reputation: 23793

Values semantics apply : transactions.push_back(*t); will push a copy of t in your std::vector.

So you still need to delete the memory allocated for the original object : any new must be match by a call to delete.


You probably don't need a new in the first place, you can just do :

Transaction t(data); 
...
transactions.push_back(t);

Note:

As pointed by Matt, Transaction t = new Transaction(data); doesn't even compile, you probably meant something like Transaction* t = new Transaction(data);

Upvotes: 4

ravi
ravi

Reputation: 10733

You either store plain objects OR pointer to objects in vector. You are drawing line somewhere in between as you are creating objects on heap and then stroing plain objects in vector.

Question is who would delete these objects?

By default store plain objects in vector. But if copying of objects is expensive OR there's no proper way to define copying for the objects OR you want to preserve polymorphic behavior then you store pointers into the container.

Upvotes: 0

Related Questions