简体   繁体   中英

is it ok to clear vector in a destructor

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() }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM