Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
 }
like image 302
SurenNihalani Avatar asked Jun 06 '12 16:06

SurenNihalani


2 Answers

  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.

like image 189
K-ballo Avatar answered Nov 10 '22 06:11

K-ballo


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.

like image 33
Jonathan Wakely Avatar answered Nov 10 '22 04:11

Jonathan Wakely