Hi folks,
this might come off as a silly question but here it is.
If I have this code:
class CtrTest {
public:
CtrTest() {
cout << "Ctr" << endl;
}
CtrTest(const CtrTest&) {
cout << "Cp Ctr" << endl;
}
};
class Wrap {
CtrTest test;
public:
const CtrTest& ret_ref() { cout << "ret_ref()" << endl; return test; }
const CtrTest* ret_ptr() { cout << "ret_ptr()" << endl; return &test; }
const CtrTest ret_val() { cout << "ret_val()" << endl; return test; }
};
int main() {
Wrap w;
cout << "phase 1" << endl;
const CtrTest test1 = w.ret_ref();
cout << "phase 2" << endl;
const CtrTest& test2 = w.ret_ref();
cout << "phase 3" << endl;
const CtrTest* test3 = w.ret_ptr();
cout << "phase 4" << endl;
const CtrTest test4 = w.ret_val();
return 0;
}
yielding this output:
Ctr
phase 1
ret_ref()
Cp Ctr
phase 2
ret_ref()
phase 3
ret_ptr()
phase 4
ret_val()
Cp Ctr
I notice that, despite what I've seen written online, doing: const CtrTest test1 = w.ret_ref();
and const CtrTest* test3 = w.ret_ptr();
is not the same at all as far as efficiency is concerned.
In the first case the copy constructor for CtrTest gets called to assign the reference to test1. In the second case it is not.
What I'm asking is: is it really recommended to return objects by reference and assigning them to "plain" variables (i.e. not references like "test2") as I've seen done countless times? Wouldn't it be better to use pointers then?
I've also noticed that ret_val() yields the same result as ret_ref(), but I chalk it up to compiler optimisations.
Regards.