A
Angus
Hello
I want to store a collection of objects in a vector. I think the best
way is for me to create each object on the free store (heap) and then
store a pointer to the object in the vector.
Eg like this:
std::vector<MyWidget*> m_widgets;
MyWidget* newone = new MyWidget;
//populate/process
m_widgets.push_back(newone);
Rather than:
std::vector<MyWidget> m_widgets;
MyWidget newone;
//populate/process
m_widgets.push_back(newone);
Reason being that with a pointer the push back does not have to do a
copy of the entire object, it simply copies the address of the object.
The only downside to pointer approach is having to delete the object
at the end but that is easy enough to do.
What other approaches could I use? Could I use a reference instead?
Any comments would be very much appreciated.
Angus
I want to store a collection of objects in a vector. I think the best
way is for me to create each object on the free store (heap) and then
store a pointer to the object in the vector.
Eg like this:
std::vector<MyWidget*> m_widgets;
MyWidget* newone = new MyWidget;
//populate/process
m_widgets.push_back(newone);
Rather than:
std::vector<MyWidget> m_widgets;
MyWidget newone;
//populate/process
m_widgets.push_back(newone);
Reason being that with a pointer the push back does not have to do a
copy of the entire object, it simply copies the address of the object.
The only downside to pointer approach is having to delete the object
at the end but that is easy enough to do.
What other approaches could I use? Could I use a reference instead?
Any comments would be very much appreciated.
Angus