0

Constructor of every object in vector is called everytime I add a new element. How do I resolve this?

I made a vector to hold the dynamic (user determined) number of objects of a class that will be created during runtime. However, every time I use the "push_back" function to add another object to the vector, the constructor of every single object in the vector is called. I suspect it's because new memory has to be allocated every addition, so I could use reserve function, but I then can't exceed that amount

27th Mar 2017, 1:09 PM
denzal maradona
denzal maradona - avatar
1 Resposta
+ 4
I think I have a solution to your problem. Your vector should be object pointers like this: std::vector<MyClass*> objectPointerVector; Next, you can create a dynamic amount of objects like this: std::cout << "Enter number of objects to create: "; std::cin >> nObjects; for (int i = 0; i < nObjects; i++) { objectPointerVector.push_back(new MyClass()); } Just remember you HAVE to delete the memory when you are done with the objects or your program. Here is how you do that: std::vector<MyClass*>::iterator iter; for (iter = objectPointerVector.begin(); iter != objectPointerVector.end(); iter++) { delete (*iter); } There are many other ways to go about this and tons of discussions about it on the internet; it just depends on what you are using it for. I hope this helps! Happy coding :) **EDIT** There is a much easier way to do this that takes advantage of the vector's ability to call destructor functions automatically, so you don't have to manually delete them: std::vector<MyClass> objectVector; cin >> nObjects; objectVector.resize(nObjects); // http://www.cplusplus.com/reference/vector/vector/resize/ // then you can call each object like this objectVector[n].objectFunction(); The destructors will be called when the end of the vector's scope has been reached, freeing up the memory.
27th Mar 2017, 9:08 PM
Zeke Williams
Zeke Williams - avatar