References make a pointer-like paper, but the address it references is immutable. When you move a reference, you're not doing anything but tinkering with the variable it references, it never changes. They are equivalent, but they must be used according to the cases in which they are requested, performing their fundamental functions. There is also a specific type of referencing that behaves differently, called rvalue reference . It is used when the variable lifetime is small .
What also changes is the way the compiler will handle the variable you have, the syntactic sugar and good practices. This is very general in this way, so let's look at an example. If you have a int f(int&)
function, you can enter either a int&
or a *(int*)
, correct - in these cases, they necessarily complement each other. Because this is the basics, a concept that came from C for C ++. If you look at the most common Windows or Linux APIs, you will notice that changing variables are always passed by pointers, since C there were no references . They have created these references to make the program safer and "handsome" because, after all, pointers are one of the most "unpredictable" things about programming errors.
If you know Assembly, the difference of a pointer is that, (analogously, not literally,) when you call a mnemonic or perform a function, it performs MNM var
, and with a reference, MNM [var]
. This is equivalent to saying that C ++ mostly treats references as pointers, pointers as references to a variable, and vice versa. They are similar, but different in practice, as the example of the function. In practice, when you have a data string in memory, ask for a pointer. If you need a change in memory variable, ask for a reference. The cleaner a code is, the less chance of making a mistake will exist.
Example:
void f(int&&);
int main()
{
int var;
int& referencia = var;
referencia = 1; // o valor de var agora é 1
std::cout << (int)&referencia; //imprime o endereço em que var se encontra, dando o ponteiro para a variável
&referencia = (int*)0; // ERRO: imutável
f(1); //imprime 1, valor literal
f(referencia); // ERRO
}
void f(int&& var)
{
std::cout << var;
}