Sorry about the confusing title, did not know what to title it.
I have this function:
static void smooth5(IntVector*& v)
{
IntVector* tmp = new IntVector();
for(int i=0; i<v->size(); i+=2)
tmp->push_back(v->at(i));
delete v;
v = tmp;
}
and in the main I do this:
IntVector* v = new IntVector();
v->push_back(0);
v->push_back(1);
v->push_back(2);
v->push_back(3);
smooth5(v);
//print the contents of v
When I print the contents of v, the output is 0 2.
But I did not understand what
IntVector*& v
really means when v is a pointer to an object on the heap. Can someone please explain?
IntVector*&declares a reference to a pointer. Using this as a function argument allowssmooth5to modify the caller’s copy ofv.It is similar to but more readable than passing a pointer to a pointer –
IntVector**.In your example,
smooth5deletes the caller’sIntVectorand points it to itstmpvariable instead.