I am working with a std::vector to hold some objects that have dynamically allocated members, and when I go to put the Things into the vector a few things happen that I am not understanding.
-
I call
push_back()and use the constructor of the objects as the argument, but for some reason it goes to the destructor of the object. why is this; it should be adding not deleting? -
I call
push_back()a second time doing the same as before, but this time it throws an illegal memory access atdbgdel.cppoperator delete (line 52). but delete should never be called in a constructor, orpush_back().
I am uncertain what sections of code are pertinent to this question as the lines in question are pretty entrenched in a method.
Edit: Code added
class Thing{
int** Array;
int size; // of square array
Point current; // location
Thing(int _n){
// allocates, and gives values to the array, and members
// only constructor
}
};
class ThingMgr{
Thing * Control;
Thing * Current;
Thing * Previous;
int size; // size of all. same use as in Thing
ThingMgr(int _n){
size = _n;
Control = new Thing(size);
Current = new Thing(size);
Previous = new Thing(size);
}
void rearrange(int _num){
std::vector<Thing> possibles;
// performs deterministic work on members
// [0] first
possibles.push_back(Thing(size)); // this succeeds
// [1] second
possibles.push_back(Thing(size)); // this fails
// more operations to be performed never reached.
}
};
You are pushing a copy of that element into the
vector. You construct a temporal element, its copy-constructor is called to create a copy within thevector, then the destructor of the temporal element is called.It’s strange that this happen on a second call, but eventually when the
vectorneeds to regrow it copies elements again.You are probably failing to provide a proper copy-constructor for the element in question.