Suppose I have complex objects, like structs containing a huge amount of members – and I want to store them in a vector.
Now vector::push_back(…) works over call-by-reference (rather than call-by-value), so in the first moment the passed object is not copied. But what about later? Does a vector internally store pointers or direct references? When the vector needs to expand, are the contained elements themselves copied or their addresses?
This finally results in the question, if – for large objects – the objects themselves should be stored in a vector or rather pointers to these objects. Is there a kind of best practice for that?
std::vector::push_backsaves copy of the object.If you need performance by avoiding copy, then you could use vector of pointers.
Or you can use some sort of smart pointer, so as to avoid managing memory yourself.
For example, you could use
std::unique_ptrif your compiler supports it:If you use pointers (or smart pointers), then copying is still there, but this time, the copy is done for pointers (or smart pointers) which is much cheaper.
From @Loki’s comment: