What kind of argument does this function take?

Hi I have a function that I don't really know what kind of argument it takes. The function looks like this:

1
2
3
4
5
void printText( const string& stringPtr)
{
    cout << stringPtr;

} // end function printText 


It sort of says string Pointer but doesn't the &-sign make it an address to a string?

/Skorpan
It takes a const reference to an std::string. The stringPtr identifier is misleading, as the function will take an std::string as its argument. The const keyword prevents the function from altering the object.

Usually, when you just need to pass an object's data without altering it, you use a const reference to avoid the overhead of copying the object. A reference is like a pointer, but it needs to be initialized to a valid object, it can't point to something else once initialized, and it behaves like the object itself (like a dereferenced pointer). This means a reference can be used as a synonym for the object it points to.

When you see a function that takes a non-const reference, assume it changes the object's state. If it's not meant to change it, it should be a const reference.
Last edited on
Thanks that cleared things up a bit. I thought there was something strange with that function.

/Skorpan
Topic archived. No new replies allowed.