I have a static map of vector pointers:
static std::map<type, std::vector<object *> > m_objects;
How should I delete the entries in this case?
I have a static map of vector pointers:
static std::map<type, std::vector<object *> > m_objects;
How should I delete the entries in this case?
If m_objects
owns the object
s pointed to by the std::vector
then delete
must be called on each object
in the std::vector
, or use a smart pointer that will automatically delete the object
s when the std::vector
is destructed (in this case when it is removed from the map
):
static std::map<type, std::vector<std::unique_ptr<object>>> m_objects;
If the object
s are not owned by m_object
s then delete
must not be called (as they are used elsewhere).
Iterate over each entry in the map, and for each entry, iterate over each entry in the vector and delete them.
for (auto it : m_objects) {
for (auto ptr : it.second) {
delete ptr;
}
}
A better solution might be to use std::unique_ptr
or std::shared_ptr
.
A better solution would be not to use a vector of raw pointers and take advantage of C++11 perfect forwarding
#include <iostream>
#include <map>
#include <memory>
#include <vector>
using namespace std;
struct object {
};
enum type {
TYPE0,
TYPE1
};
typedef std::map<type, std::vector<std::unique_ptr<object> > > long_type;
static long_type m_objects;
int main() {
std::vector<std::unique_ptr<object>> vec;
vec.push_back(std::move(std::unique_ptr<object>(new object))); // make_unique in C++14
m_objects.insert(std::pair<type, std::vector<std::unique_ptr<object>>>(TYPE0, std::move(vec)));
long_type::iterator it = m_objects.find(TYPE0);
m_objects.erase(it);
cout << m_objects.size(); // 0
return 0;
}
This way you don't have to worry about calling delete
on each of your allocated objects (the map will not do it by itself).
As of inserting and deleting elements, the same stands for a normal std::map
with insert and erase.