Reference in C ++

Source: Internet
Author: User

Basic knowledge:
References and pointers look very different (including definitions, assignments, and usage), but essentially they are similar. Both pointers and references can point indirectly to a variable. You can also say that, pointer and reference introduction and an indirect layer.
In C ++, only pointers and references support polymorphism, which is not accidental.

Let's first look at the referenced syntax. There is no need to be a bunch of standard references at first, and we only need a small piece of well-designed code.
Int M = 10;
Int n = 20;
 
Int * P = NULL; // pointer Definition
P = & M; // pointer assignment
P = & N; // the pointer can be assigned a value again.
M = * P; // pointer usage

Int & Rn = N; // definition and value assignment of the Reference
Rn = m; // reference

We use this simple code to illustrate the differences between pointers and references:
1. There is no null reference, and the pointer can be a null pointer.
2. The reference must be initialized at the same time as the definition. The pointer can be not initialized after the definition.
3. The reference is specified after initialization and cannot be re-specified. The pointer can be re-specified.
Int & Rn = N;
In this sentence, a quote's past and present are doomed. referencing RN is an alias of Variable N. Modifying RN is modifying N, and modifying N is also modifying rn. Oh, it seems like a loyal couple lives together,
Review the advice in <Effictive C ++>: "whenever you see a reference, you should immediately ask yourself what the other name is, because it must be another name of something. "Fortunately, in most cases,
It is not difficult to find another referenced name.
Rn = m; // reference
What if I have to re-assign a value to the reference? Here, rn still points to n. You just assigned the m value to n through reference.

Const reference:
Int & rn = 5; does not exist, but const int & rn = 5; does exist. In fact, there is nothing strange. The type of a constant should be const, in C ++, this is not the case.
However, I still want you to understand the meaning of const int & rn = 5;. The reference is the alias of the variable, not the alias of a constant. The Code should be true, the compiler must perform the following conversions:
Const int temp = 5;
Const int & rn = temp;
Maybe someone should say that I am too doggy: :) what if I understood rn as a reference of constant 5? Well, there seems to be no problem.
The biggest function of const reference is to accept non-lvalue initialization.
Void print (const string & s)
{
}
Print ("wgs ");
If there is no const reference, print ("wgs"); here cannot be compiled
Int n = 10;
Const int & rn = n;
Interestingly, the Code is also true. Here, the meaning is to declare rn as a reference to Variable n, and use const to restrict rn modification.
But strictly speaking, isn't the reference and referenced variable types different here? Well, the stricter statement should be the non-CV-qualiifer <const In the eccentric relation of CV-qualifiers, that is
After adding const, only the type constraints are enhanced.

Pointer Reference:
Int * & p2 = p;
There is a reference to the pointer. Here p2 is a reference to the pointer p. What's strange? The pointer is also a variable. Maybe it's strange to remember the * & syntax.
Int & nn = rn; // Error
But there is no reference pointing to the reference. The & syntax should be an operator.
Int * p3 = & rn;
There is a pointer to the referenced address. The referenced address is the address of the referenced variable, because the reference is only the alias of the referenced variable, and the pointer here is just a common pointer.
Int & * p4 = rn; // Error
But there is no pointer pointing to the reference. At this time, someone should be angry. Well, I admit, the compiler will report errors, so don't remember. If anyone dares to test you, you can fight with him.

Reference parameters:
Void swap (int & a, int & B)
{
Int temp =;
A = B;
B = temp;
}
Finally, the reference is the most used. The function parameters have the difference between passing a value and passing a reference, some people may remember the '* or even **' syntax that has to be used to declare a parameter in C to implement parameter transfer reference, and remember
The function is constantly referenced, and C ++ directly supports reference, which is much simpler.
But what if we only have pointers?
Int m = 10;
Int n = 20;
Int * pm = & m;
Int * pn = & n;
Swap (m, n );
Swap (* pm, * pn );
Pointers can be converted to references. Here, after the pm is referenced, m is used. Therefore, the referenced parameter a becomes the alias of m. Some people may like int & nn = * (int *) n; and so on to explain the conversion from pointer to reference, but I still like
More simply, "reference is the alias of a variable ".
Void print (const int &)
This const reference parameter method is also very common. The meaning here is that the parameter is still referenced, but it cannot be modified within the function because the const type is declared, the benefit of doing so is efficiency.

Reference return value:
Struct Point
{
Double x;
Double y;

Point & operator = (const Point & other)
{
If (this! = & Other)
{
X = other. x;
Y = other. y;
}

Return * this;
}
};
The return value of a function is of the reference type. The example here is about Operator overloading. This is not an accident. The reference was introduced to support Operator overloading, let's emphasize again,
"Reference is the alias of a variable". The most direct benefit of returning a function value to a reference type is efficiency. On the other hand, for operate =, we do need to return lvalue, this is exactly where aliases can show their talents.
It seems simple enough to return a function as a reference type, but I hope you will remember the following terms about reference in <Effictive C ++>:
Clause 30: Do not pass back the member variables in the object in the reference of the return value of the object member function, unless the reference is const
This can easily damage the encapsulation of objects.
Clause 31: Do not pass back the reference of a local object in the function in the reference of the function return value.
Because the partial objects in the function disappear at the end of the function, the pointer obtained by new in the function returned value reference refers to the object, this violates the principle that pointer distribution and release must be symmetric.

Reference of member variables:
Template <class T>
Class RefHolder
{
T & m_ref;
Public:
Refholder (T & ref): m_ref (REF ){}
Operator T & () const
{
Return m_ref;
}
};
If the member variables in the class are also variables, Can you define references to the member variables? Certainly, there is no doubt at all, but the reference to the member variable also brings about a problem. We say that the reference should be defined at the same time
Initialization, but it is impossible to declare a reference pointing to a member variable in the class definition and specify a variable pointing to the reference, this is because no real variable exists. no way. You can only use
An indirect method is to point to the reference initialization of the member variable, which is the initialization line.
T & m_ref;
A reference is declared here, and a template is used here. Of course, you can replace T with any specific type.
Refholder (T & ref): m_ref (REF ){}
The initialization line of the constructor initializes the reference to the member variable.

Dangerous type:
"Reference is the alias of a variable". What if the referenced type is different from the variable type?
Int nn = 20;
Const short & s = nn;
Nn = 0;
Printf ("% d", S, NN );
Here, we declare that S is a reference to Nn, but the type of S is different from that of NN. This is against the alias's intention, but most compilers will make the following conversions smartly:
Short temp = nn;
Const short & s = temp;
The compilation is successful, but what about the execution?
Printf ("% d", s, nn );
The printed result is: 20, 0
Well, most compilers can detect this bug if they set a high error level, but some compilers won't give any prompts at all. Alas, please, you are just a reference, it's an alias of others.
Is it a trick to change people's identities? Honestly declare a reference and initialize it. The connection type must be consistent.

Function alias:
Although not commonly used, the reference can actually point to a function:
Void print (const string & s)
{
}
Void (& pfun) (const string &) = print;
Pfun ("wgs ");
The pfun here is the alias of the print function.

For More information, see <More Effective C ++>.
For more information, see <C ++ advanced programming>.
For more information, see <strong tive C ++>.
For more information, see <Imperfect C ++>.
For more information, see <C ++ language design and evolution>.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.