Pregunta

How do reference-type functions work when they are used as l-values? I mean, what is the order in which things get done in such a function so that the return variable gets a new value and how is it different from what happens in a normal r-value function?

For example in the following piece of code,

double& matrix::operator()(int i, int j) const //parenthesis operator
{
  if (!validdex(*this,i,j)) throw(-23); //index out of bounds
  return mat[(i-1)*ncols+(j-1)]; //A(i,j)=mat[(i-1)*ncols+(j-1)]
}

which is used to overload parentheses for instances of a class named matrix (validdex chacks if k is a valid index for the matrix), I need to know how the way in which the function (the paranthesis operator in this case) is processed differs when it is used as an r-value (to get mat[(i-1)*ncols+(j-1)]) from when it is used as an l-value (to set the value of mat[(i-1)*ncols+(j-1)]).

Sorry if the question is vague or if it sounds too basic. I tried to find the answer on the web but I didn't find anything besides some very basic tutorials on l-value functions with only a return line and nothing else.

¿Fue útil?

Solución

When a function returns a reference you can think of it as though the function were returning a pointer. Functions that return references do not interact in any special way with the calling code. Such special interaction is not necessary to use a function call expression as an lvalue: The function returns its pointer and then it's done; The calling code just uses the pointer value.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top