general rule of thumb: reference anything bigger than an integer. strings, vectors, classes, etc all should be passed around by reference. This just saves a lot of time spent copying data, its a performance hit to copy when you do not need to. If you do not want to change it, put const on it. If you do want to change it, document it as a side effect.
this is useful if you have the same thing twice or confusion. avoid unnecessary thising.
foo::func(string sigh)
this->sigh = sigh; // you need to qualify this->sigh because the parameter has same name as the class variable.
foo::func(string sigh_in)
sigh = sigh_in; //no need for a this, it can tell which is which.
and finally in the second example I could still say this->sigh but it is just visual clutter best avoided. That is, just say: return name;
that said..
1) references are not true pointers. the compiler may directly use the same token for the reference and the real item without a third party pointer in the middle, and it WILL do this where it can. There are some places where it may have to use a pointer, but I do not know compiler and code generation well enough to say when anymore. That is if you have ref that is referring to x, and x is at address 1234, the compiler may generate assembly using address 1234 for both x and ref without an extra layer of access via a true pointer.
string & and string are different.
but they are used the same way:
s = func(); //works whether func returns reference or copy. it matters under the hood, but both will work.
its that under the hood that is getting you.
Maybe this will clear up some of the mystery:
const string & getName() const {return this->name;} //returns a reference to the actual value. you could say this... const string &ref = object.getname(); and then, if you did object.setname(), ref HAS ALSO CHANGED. you are not doing this, you are copying whats in the ref to a target.
const string getName() const {return this->name;} //this is just going to copy the data.
in action:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
class foo
{
public:
int x;
const int &getx() {return x;}
};
int main()
{
foo f;
f.x = 1234;
const int &xref = f.getx();
cout << xref << endl;
f.x = 777;
cout << xref << endl;
return 0;
}
|
C:\c>a
1234
777