Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vectors of references to objects

Tags:

Is it legal to have a vector of references to objects, like the following?

vector<Agent&> seenAgents; 

Which would for example be populated by some, but not all of the objects in the scene?

I have a vector of Agent objects, but the vector outlined above should hold references to only the ones each agent can currently see - meaning that the references will be being added and removed all the time.

Is this something the language will allow? And in addition, is there anything else I need to be aware of? If I remove a reference from the vector does it persist anywhere? Is it a memory leak?

I seem to be getting this error on the line declaring the vector:

error C2528: 'pointer' : pointer to reference is illegal 

Is this something directly to do with the line or is it most likely occurring somewhere else? It's being initialised in the constructors initialiser list like this:

seenAgents(vector<Agents&>()) 
like image 432
Dollarslice Avatar asked Nov 20 '11 09:11

Dollarslice


People also ask

Can a vector contain references?

You can't take the address of a reference, since attempting to do so would result in the address of the object being referred to, and thus you can never get a pointer to a reference. std::vector works with pointers to its elements, so the values being stored need to be able to be pointed to.

Does vector erase destroy the object?

Yes. vector::erase destroys the removed object, which involves calling its destructor.


1 Answers

You can't have vector of references, as a reference is not copyable assignable and all STL containers are supposed to store copyable assignable items.

But you can make the container to hold pointers. Like this:

vector< Agents* > seenAgents; 

This is a little dangerous. You need to be sure that these pointers will remain valid. I mean - if someone deletes an object, pointed by a pointer in this container, the pointer becomes invalid. You need to be sure that this will not happen, because you can't check it (you can't check for NULL, because a pointer will not become NULL, if someone deletes the pointed object).

The best solution here (provided by container with pointers) would be to use some smart pointers - some with reference count, for example; they will guarantee you that the object will exist and that the pointer is valid. And in case that the object, pointed by the smart pointer, is destroyed, you can check it for NULL.

like image 98
Kiril Kirov Avatar answered Sep 23 '22 08:09

Kiril Kirov