1

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Avb Avb
  • 545
  • 2
  • 13
  • 25

3 Answers3

4

If m_objects owns the objects 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 objects 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 objects are not owned by m_objects then delete must not be called (as they are used elsewhere).


See What C++ Smart Pointer Implementations are available?

Community
  • 1
  • 1
hmjd
  • 120,187
  • 20
  • 207
  • 252
1

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.

Bart van Nierop
  • 4,130
  • 2
  • 28
  • 32
1

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;
}

http://ideone.com/5L4g1x

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.

Marco A.
  • 43,032
  • 26
  • 132
  • 246