user3455638
user3455638

Reputation: 609

How quickly dealocate map which contains dynamically allocated memory as a value?

Map consists of string as a key and objects of A as a value. Function clear() from std::map/std::unordered_map won`t call destructor. I have to take care of dealocating memory by my self when I want to clear the map. Is it only one way to dealocate memory using for loop? Code:

#include <iostream>
#include <unordered_map>
class A
{
public:
    A() { std::cout << "A()" << std::endl; }
    ~A() { std::cout << "~A()" << std::endl; }
};
int main ()
{
  std::unordered_map<std::string, const A*> mymap = { {"house",new A()}, {"car", new A()}, {"grapefruit", new A()} };
  //mymap.clear();//won`t call destructor
  for(const auto &i : mymap)
      delete i.second;      //dealocate value
  mymap.clear();            //clear whole object from tha map
}

Is it possible to do this faster, e.g. without using for loop?

Upvotes: 1

Views: 882

Answers (2)

Curious
Curious

Reputation: 21510

Yep! Use unique_ptr and automate this.

(Note how I have converted const A* to std::unique_ptr<const A>)

#include <iostream>
#include <memory>
#include <unordered_map>

class A {
public:
    A() { std::cout << "A()" << std::endl; }
    ~A() { std::cout << "~A()" << std::endl; }
};

int main() {
  std::unordered_map<std::string, std::unique_ptr<const A>> mymap;
  mymap["house"] = std::make_unique<A>();
  mymap["car"] = std::make_unique<A>();
  mymap["grapefruit"] = std::make_unique<A>();

  mymap.clear(); // Will call destructor!
}

Upvotes: 5

Jesper Juhl
Jesper Juhl

Reputation: 31464

Use a map of std::unique_ptrs and just clear() it. Or just hold A objects in the map rather than pointers.

Upvotes: 3

Related Questions