I am learning about memory management and not quite sure how how to manage the delete and/or destructor policy.
Suppose I have the following template:
template <typename X>
class DBContainer {
private:
vector<vector<X>> db;
size_t dbSize;
public:
DBContainer(size_t n = 100) {
dbSize = n;
<vector<vector<X>> *tmp = new vector<vector<X>>(dbSize);
db = std::move(*tmp);
// db = std::swap(tmp);
delete tmp;
}
~DBContainer() { /* how should I delete `db`? */ }
// ~DBContainer() = default;
};
How should I set the destructor policy for db? I understand that for a raw pointer, std::move only copies the intermediary vector of vectors to db; therefore, I still need to delete the intermediary dynamically allocated vector. I could be wrong but I believe it is the same for std::swap.
But then, at the end of the program, how should I manage the destructor policy for db? Do I simply set it to default?
Anything you construct dynamically with
newneeds to bedelete'd when you are done using it.std::unique_ptrcan help with that by callingdeletefor you when it is itself destructed, eg:It doesn't matter that the content of
tmpis moved todb,tmpitself still needs to bedelete'd.However, since
dbis not being dynamically constructed vianew, there is no need todeleteit. It will be destructed automatically when its owningDBContainerobject is destructed. Only your temporaryvectorthat is being constructed vianewneeds to bedelete'd. But even that can be avoided, by simply not constructing the temporaryvectordynamically at all, eg:Alternatively:
That being said, you don't actually need the temporary
vectorat all. You can (and should) initializedbdirectly, in the constructor's member initialization list, eg:And technically, you can get rid of
dbSizetoo, just usedb.size()whenever needed: