How safe is returning a value by reference?
Hi,
I have seen an interesting example of applications of returning a value by =
reference from method. But is it really safe? If not could you give me some=
clear examples which will show when it is unsafe? Stroustrup has given in =
TC++PL among others following sample:
class Matrix {
friend Matrix& operator+(const Matrix&, const Matrix&)
};
He have claimed that above code is proper but it causes problems with memor=
y allocation. I am not sure what he means.
He has stated that:
1. a reference to a result will be passed outside the function as a referen=
ce to a value passed from a function, so that value can't be an automatic v=
ariable.
2. Operator is often used in an expression more than once so it can't be a =
local static variable.
3. Copying a passed value is usually cheaper (with respect to time of execu=
tion, size of code and size of data).
I would like to know what are reasons for which above sentences holds. Agai=
n, I would be grateful for clear examples.
Next - Stroustrup claim that passing by reference could cause an improvemen=
t of efficiency (however his third from above statements shows that not nec=
essarily). Ok, but I wonder what happens in code like that:
Matrix a, b;
Matrix c;
c=a+b;
If operator+ returns a value by value then that value is returned by return=
this ; inside operator+ definition. Then a compiler can directly assign c =
to newly created object.
If operator+ returns a value by a reference then a copy has to be created -=
in other case c would be a same object which a+b is. But syntax of the ass=
ignment denies it - a reference is nothing other than a synonym for an obje=
ct so above instruction has to mean that a value is assigned (and not objec=
t).
So as far as I understand when an assignment or an initialization is execut=
ed returning a value by a reference has no impact for capacity. Am I right?
Later, Stroustrup has given an example of the technique about which he has =
said that it causes that a result is not copied:
const int max_matrix_tem = 7;
Matrix& give_matrix_tem() {
static int nbuf = 0;
static Matrix buf[max_matrix_tem] nbuf = 0;
return buf[nbuf++];
}
Matrix& operator+(const Matrix& arg1, const Matrix& arg2) {
Matrix& res = give_matrix_tem();
//...
return tem;
}
As far as I understand above code should help to improve efficiency if we h=
ave
an expression in which there is more than one operator+. But when an assign=
ment to give_matrix_tem should be executed? What should be assigned to give=
_matrix_tem? It looks that in the situation in which buf is full filled a v=
alue which give_matrix_tem() will return next will be old one. And how abov=
e code make that a copying of value is avoided?
Thanks in advance for responses,
Greetings.