Correct way to initialize a map and delete in C++

30,478

Solution 1

  map<string, a> myMap;
  ....
  myMap = new map<string, a>;

Here myMap is not a pointer, so the initialization with new is incorrect. Perhaps you are looking for:

  myMap = map<string,a>();

to copy into myMap a default initialized map.

Note that you don't need (and in fact can't) delete myMap, as is not a pointer. It's a member variable, and the compiler will take care of automatically destroying it when your class is destroyed.

Solution 2

void aClass::method(int a)
{
  myMap.clear();  // ensure it starts off empty
  // Addition of elements;
}
void aClass::amethod(int b)
{
  // retrival of elements
  myMap.clear();  // maybe not necessary
}

The object myMap already exists inside an instance of aClass and is constructed when its containing instance is constructed. You don't need to use new to create it, that's a Java and C# feature, where variables are just references to some instance on the heap and everything is garbage-collected. In C++ it's easier to make data members a value rather than a pointer or reference to some other object.

Share:
30,478
SurenNihalani
Author by

SurenNihalani

Updated on June 07, 2020

Comments

  • SurenNihalani
    SurenNihalani almost 4 years

    I am trying to create a static map declared in the constructor of my class. This map is to be initialized and filled with data in one method and free'd in another method. Is this the correct way to do it?

    using namespace std;
    #include <map>
    
    struct a {
         string b;
         string c;
    }
    
    class aClass:public myClass
     {
     public:
          aClass();
          virtual ~aClass();
    
     private: 
          map<string, a> myMap;
          void method(int a);
          void amethod(int b);
     }
     void aClass::method(int a)
     {
          myMap = new map<string, a>;
          // Addition of elements;
     }
     void aClass::amethod(int b)
     {
          // retrival of elements
          myMap.clear();
          delete myMap;
     }