c++ - Deleting objects from a vector of pointers -


i have looked @ number of questions similar still can't manage fix this.

consider simple class:

class obj { public:     obj(int moose);     ~obj();  private:     int* val; };   obj::obj(int num) {     val = new int;      *val = num; }   obj::~obj() {     printf("cleanup");     delete val; } 

now want have vector of pointers objs. source details problem:

int main(int argc, const char * argv[]) {     std::vector<obj*> objs;      obj* o = new obj(10);      objs.push_back(o);      objs.erase(objs.begin() + 0);      // should have been deleted - want destructor have been called     // have tried delete objs[0], casting , deleting it.      return 0; } 

the destructor in obj called when program has finished. want called when object erased vector.

clarification: trying delete object using reference vector. cannot so. know vector doesn't deallocate memory. removes reference vector. can provide code delete object , call destructor using reference vector.

edit:

even after adding:

auto = objs.begin() + 0; delete *it; objs.erase(it); 

as suggested, destructor of obj not fire.

as number of comments have pointed out, vector.erase removes elements vector. not try delete associated memory.
delete associated memory explicitly, need to:

int main(int argc, const char * argv[]) {     ...      auto = objs.begin() + i;     delete *it;     objs.erase(it);  } 

actually, in case:

int main(int argc, const char * argv[]) {     std::vector<obj*> objs;      obj* o = new obj(10);     objs.push_back(o);          auto = objs.begin();     delete *it;     objs.erase(it);  } 

there number of other inconsistencies code and, better solutions you're trying do, such as:

  • using vector<obj>:

    int main(int argc, const char * argv[]) {     std::vector<obj> objs;     objs.emplace_back(10);          auto = objs.begin();     objs.erase(it); } 
  • if need dynamically allocate objects, reason not want vector handle that, can use shared_ptr or unique_ptr, take care of deallocation you:

    int main(int argc, const char * argv[]) {     std::vector<std::unique_ptr<obj>> objs;      objs.emplace_back(new obj(10));          auto = objs.begin();     objs.erase(it); } 

Comments

Popular posts from this blog

php - Magento - Deleted Base url key -

javascript - Tooltipster plugin not firing jquery function when button or any click even occur -

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -