Token &
In C ++, this token has many meanings:
As a binary operator, the operator is a bitwise "and".
0b0011 & 0b0110; // 0b0010
As a unary operator, the operator takes the address of a variable.
Type a; Type * ap = & a; // указатель на переменную типа Type
As part of the type declaration of a type modifier.
Type & r; // ссылка на переменную типа Type
Token *
This token has the same set of values.
As a binary operator - the multiplication operator.
3 * 5; // 15
As a unary operator, the dereference operator (taking the value) of a variable.
Type a; Type & ar = * a; // ссылка на переменную типа Type
As part of the type declaration of a type modifier.
Type * r; // указатель на переменную типа Type
References as values
Working with links is like working with their values. You cannot override a link to point to another object. Almost the entire syntax for the link and for the variable values are the same. Links are branded as Type & name . And in the future, behave like ordinary permenenye containing value.
struct Type { int a; } Type o; Type & r = o; oa = 1; // ok ra = 2; // ok
The reference variable can be assigned to the object and vice versa:
Type & ref = o; Type val; ref = val; val = ref;
Passing as an argument to a function is also an assignment, so the previous one is also true for them:
void fun1(Type x) {} fun1(o); // ok fun1(r); // ok void fun2(Type & y) {} fun2(o); // ok fun2(r); // ok
Why can not assign pointer reference.
One of the most important reasons for this is that the pointer may contain the address of a non-valid object. This process is given to programmers:
void funcp(Type* p) { if (p == nullptr) { Type & r = &p; // Здесь ОС пошлет сигнал и программа аварийно завершится } else { Type & r = &p; // Здесь все должно быть хорошо } }
Also, the pointer can be reassigned, but in the case of passing the pointer to the function it does not matter. There are a number of other cases where links and pointers serve very different purposes, but this is a reason for a separate article.
&rObjis a link? - AnT 10:02 pm