Passing references to pointers in C++

Alex picture Alex · May 5, 2009 · Viewed 147.6k times · Source

As far as I can tell, there's no reason I shouldn't be allowed to pass a reference to a pointer in C++. However, my attempts to do so are failing, and I have no idea why.

This is what I'm doing:

void myfunc(string*& val)
{
    // Do stuff to the string pointer
}

// sometime later 
{
    // ...
    string s;
    myfunc(&s);
    // ...
}

And I'm getting this error:

cannot convert parameter 1 from 'std::string *' to 'std::string *&'

Answer

Chris picture Chris · May 5, 2009

Your function expects a reference to an actual string pointer in the calling scope, not an anonymous string pointer. Thus:

string s;
string* _s = &s;
myfunc(_s);

should compile just fine.

However, this is only useful if you intend to modify the pointer you pass to the function. If you intend to modify the string itself you should use a reference to the string as Sake suggested. With that in mind it should be more obvious why the compiler complains about you original code. In your code the pointer is created 'on the fly', modifying that pointer would have no consequence and that is not what is intended. The idea of a reference (vs. a pointer) is that a reference always points to an actual object.