Proper form when working with vectors

If, for instance, I have a function similar to this to initialize objects (don't take it too literally):

1
2
3
4
5
6
7
std::vector<Object> allObjects;

void Function()
{
  Object newObject;
  allObjects.push_back(newObject);
}


And later in the code, there are a few places where the function gets called or a loop where the function is run multiple times, it fills the vector with multiple, independent objects. It clearly works as intended (so far, anyway), however, my question is: Is this an acceptable way to initialize multiple objects? Or should the vector be fill with pointers to dynamically allocated objects?

The way I saw it was even if I use pointers, the same memory must be allocated for each instance of Object, so why not just fill the vector with actual objects?
so why not just fill the vector with actual objects?

Yep. It works fine. Thats what I do.
Last edited on
Actual objects have some "advantages":

Not exactly same memory. An object in vector consumes heap to hold the object. A pointer in vector to object in heap consumes heap to hold one object and one pointer.

The destructor of vector deletes the objects in vector, but who deletes objects if the vector has only pointers? (Recommended solution: use smart pointers rather than raw pointers.)


Then again, what if you have very expensive-to-copy objects or non-copyable objects? Vector operations can silently copy elements. Pointers, even smart ones, are cheap to copy.
Yes, but not having to deal with dynamically allocated memory is much easier. I know they are incredibly useful, but pointers and objects are just a pain to me. Thanks.
Topic archived. No new replies allowed.