I've got a vector std::vector<MyClass> myclass_vec(10)
with 10 initialized objects of MyClass
. Now I would like to loop over this vector and store a reference to every MyClass
object in another vector std::vector<MyClass> myclass_vec_refs
. The reason why I would like to store references is so because I don't have to copy the objects and obviously, refer to the same object as in myclass_vec
.
For some reason, this doesn't work out as aspected. Do I have to declare std::vector<&MyClass> myclass_vec_refs
like so?
As I was looking through other questions asked here I read about std::unique_ptr
. If I change std::vector<std::unique_ptr<MyClass>> myclass_vec(10)
then I wouldn't able to have a reference or pointer in myclass_vec_refs
since they are declared unique. Correct me please if I'm mistaken.
Another approach was using std::shared_ptr
. Since it holds a reference counter I would be able to have myclass_vec_refs
point to objects in myclass_vec
, but I read this introduces quite some overhead and share_ptr should only be used as a last resort.
I also don't know if referencing like I'm attempting works out. What happens if an object in myclass_vec
is deleted? Is the myclass_vec_refs
vector resized by -1 since the object doesn't exist anymore or is it just pointing to bad memory?
Is it possible to emplace_back
a reference in the myclass_vec_refs
vector? Since this creates the object in-place I guess this doesn't work and only push_back
can be used?
You cannot make a vector of references. Why?
A reference must refer to an actual object at all times, and vectors by design must be able to create "empty" objects (i.e. default constructor) dynamically for you.
You can however create a vector of pointers.
If the other vector is modified in any way, your pointers will become invalid. If this is a problem to you, use a map or set instead.