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
new
needs to bedelete
'd when you are done using it.std::unique_ptr
can help with that by callingdelete
for you when it is itself destructed, eg:It doesn't matter that the content of
tmp
is moved todb
,tmp
itself still needs to bedelete
'd.However, since
db
is not being dynamically constructed vianew
, there is no need todelete
it. It will be destructed automatically when its owningDBContainer
object is destructed. Only your temporaryvector
that is being constructed vianew
needs to bedelete
'd. But even that can be avoided, by simply not constructing the temporaryvector
dynamically at all, eg:Alternatively:
That being said, you don't actually need the temporary
vector
at all. You can (and should) initializedb
directly, in the constructor's member initialization list, eg:And technically, you can get rid of
dbSize
too, just usedb.size()
whenever needed: