1

I'm basically trying to pass by reference, so that the changes wrought by the function upon the vector are permanent outside the scope of the function. Am I correct in thinking that passing a vector of pointers is sufficient to accomplish this on its own? It makes complete sense in my head, but I just want to confirm I'm not making an error here somehow.

void updateCursors(vector<cursor*> cursors)

This should be sufficient to change the data in the objects pointed to by these pointers, yes?

porque_no_les_deux
  • 479
  • 1
  • 6
  • 18

2 Answers2

2

You can pass the vector by reference -

vector<cursor*>& cursors

But you should not be holding pointers in a vector. The recommended way is to hold objects that are copyable/movable -

vector<cursor>& cursors
Superman
  • 3,027
  • 1
  • 15
  • 10
1

"This should be sufficient to change the data in the objects pointed to by these pointers, yes?"
When you pass a vector to this function, copy will be created (since it's passing by value), but since it's vector of pointers, YES, changes to objects will be visible outside.

But it would be still better to pass it by reference so that redundant copy is not created:

void updateCursors(vector<cursor*>& cursors)

Also note, that there's ugly memory management connected with using naked pointers. I suggest you use vector of objects if possible (vector<cursor>) or if you really have a good reason to use pointers, then I suggest you to use smart pointers (shared_ptr<cursor> instead of cursor*). This question could help you: RAII and smart pointers in C++

Community
  • 1
  • 1
LihO
  • 41,190
  • 11
  • 99
  • 167