Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it ok to clear vector in a destructor

Tags:

c++

vector

class M {
};

class E {
   public:
     ~E();     
   private:
    MyVector mv;

}; 

E::~E() {
   mv.clear()
}

typedef MyHashMap<M*, E*> EMap;
typedef MyHashMap<M*, E*>::iterator EMapItr;

class A : public class Base {

    public:
        ~A();
        const EMap& getEMap() { return p_emap};  
        virtual void  func();

    protected:
        EMap p_Map;
};

A::~A() {
   EMapItr eMItr = p_Map.beginRandom();
   for(; eMItr; ++eMItr) {
      delete eMItr.value();
   }
}
class DB {
    public fill(EMap* p_Map);
};

class Derived: public A {
    private:
       DB dp;   
};

class GUI {
    public:
      void guiFunc();  
}

void GUI:guiFunc() {
   Derived* d = new Derived;
   d->func(); 

}

void Derived::func() {
   db.fill(&p_map);
}

Please note MyHashMap is my customised hashmap . the functionality is same as std:hashmap Please note MyVector is customise form of std::vector . the functionality is same as std:vector

I do not want to delete Pointer of M class M*

is the following code correct or do yo see any problem in the same

A::~A() {
   EMapItr eMItr = p_Map.beginRandom();
   for(; eMItr; ++eMItr) {
      delete eMItr.value();
   }
}

Also do we need to clear the vector as below or it will be automatically taken care E::~E() { mv.clear() }

like image 332
TechEnthusiast Avatar asked Jan 23 '26 04:01

TechEnthusiast


1 Answers

standard library containers don't need to be cleared in destructors because they take care of their own memory management. It is best to do the same with you custom containers because that is generally expected and anyway the best way to avoid memory issues.

like image 138
stefaanv Avatar answered Jan 24 '26 21:01

stefaanv