The 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 must be initialized and filled with data in one way and free in another method. Is this the right way to do this?

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; } 
+6
source share
2 answers
  map<string, a> myMap; .... myMap = new map<string, a>; 

Here myMap not a pointer, so initialization with new is incorrect. You may be looking for:

  myMap = map<string,a>(); 

to copy the myMap initialized map to myMap .

Note that you do not need (and actually cannot) delete myMap , as it is not a pointer. This is a member variable, and the compiler will take care of automatically destroying it when your class is destroyed.

+9
source
 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 myMap object already exists inside the aClass instance and is built when building its containing instance. You do not need to use new to create it, that is a Java and C # function, where the variables are just references to any instance on the heap, and everything is going to garbage. In C ++, it's easier to make data members a value, rather than a pointer or a reference to some other object.

+1
source

Source: https://habr.com/ru/post/917463/


All Articles