Deep parsing of reference types in C + + _c language

Source: Internet
Author: User

C + + has one more type than C to do except for a variety of class types: references. This variable is not like a variable, the pointer is not like a pointer, I did not understand it before, look at the program encountered a reference is a blur of the past. Recently put a good look at the reference to a small harvest, the special public in the community, so that the beginning of the scholars to share.

A reference refers to a reference to an object. So what is an object? Objects in the narrow sense of C + + refer to variables declared using complex data types such as class, struct, union, etc., such as MyClass myclass,cdialog Mydlg, etc. A generalized object also includes a variable declared with a simple type such as int,char,float, such as int A,char B, and so on. I refer to the term "object" in the context of a generalized object. C++
The beginners ' concept of this generalized object is very helpful to the reference book, because most of the books use the word "object", but there is no mention of the concept of both broad and narrow.

One. Basic attributes of a reference
Let's first declare a reference and use it to get a preliminary understanding of the reference.
Example one:

Copy Code code as follows:

int v,k,h;
int &rv=v;
rv=3; The value of V also becomes 3 at the same time.
v=5;
k=rv+2; At this time k=5+2=7.
h=12;
Rv=h;
rv=20;

The 1th sentence declares three objects (simple variables).

In the 2nd sentence, a reference is declared, called the RV, which has the type int, or it is a reference to the type int, and it is initialized with the object V "binding" of type int. At this point the RV is called the reference of Object v.

The 3rd sentence assigns the value of the RV to 3. The magic of the reference is right here, changing the value of the reference also changes the value of the object that is bound to the reference. So at this point the value of V also becomes 3.

The 4th sentence changes the value of V to 5, at which point the value of the reference to V is changed to 5. So the value of K in the 5th sentence is 5+2 equals 7.

The above 5 sentences illustrate the relationship of references and their bound objects: in numerical terms they are linked, change you also change me, change I will change you. In fact, accessing the object and accessing the object's references means accessing the same memory area.

The 6th, 7, and 83 sentences illustrate another characteristic of the reference: one-woman. What do you mean? When you bind a reference to an object in a quoted statement, the reference is always bound to the object and cannot be changed. So that's why I used the word "binding." And the pointers are different. When the pointer is initialized to an object in the declaration statement of the pointer, the pointer can then change to another object if necessary in the future. Therefore, assigning the RV to H in the 7th sentence does not mean that the reference RV is rebind to H. In fact, the 7th sentence is just a simple assignment statement, and after the execution, the RV and V values all turn to 12. After the 8th sentence is executed, both the RV and V are 20, while H remains unchanged at 12.

A reference also has an attribute: the declaration must be initialized, both to indicate what object the reference is bound to. You know the pointer can not initialize the declaration, the reference is not. So the following statements will not compile:

Copy Code code as follows:

int V;
int &rv;
Rv=v;

Let me cite one more example:
Case TWO:
Copy Code code as follows:

Class MyClass
{
Public
int A;
...
...
};

MyClass MyClass;
myclass& Cc=myclass;
myclass.a=20; Equivalent to Cc.a=20
cc.a=60; Equivalent to Myclass.a=60


As you can see from the above examples, no matter how complex the object is, using the object's reference or using the object itself is the same in syntax format, in essence we all use the same area in memory.

The syntax for taking a referenced address and the address of an object is the same as using the address operator "&". For example:

Copy Code code as follows:

int i;
int &ri;
int *pi=&ri;//The function of this sentence is the same as int *pi=&i.

Of course, the result is the same as taking the address of an object and the address of the reference to the object.

Two. The role of references in the transfer of function parameters
Now let's get a better understanding of references through the transfer mechanism of function parameters. There are three ways to pass arguments to a function in C + +: 1, passing the object itself. 2, passing a pointer to the object. 3, passing the reference of the object.

Example three:

Copy Code code as follows:

Class MyClass
{
Public
int A;
void method ();
};

MyClass MyClass;

void Fun1 (MyClass);
void Fun2 (myclass*);
void Fun3 (myclass&);

FUN1 (MyClass); MYCLASS.A=20 does not change after the function call is performed.
Fun2 (&myclass); After performing the function call, the myclass.a=60 is changed.

Fun3 (MyClass); After performing the function call, the myclass.a=80 is changed.

Note that fun1 and Fun3 's arguments prove again that the use of objects and references to objects is the same in grammatical format.

void Fun1 (MyClass MC)
{
mc.a=40;
Mc.method ();
}

void Fun2 (Myclass* MC)
{
mc->a=60;
Mc->method ();
}

void Fun3 (myclass& MC)
{
mc.a=80;
Mc.method ();
}


We have a MyClass type Object MyClass and three function fun1,fun2,fun3, each of which requires the object itself as an argument, a pointer to an object, and a reference to an object as a parameter.

Look at the FUN1 function, which uses the object itself as a parameter, and this way of passing arguments is called the value-transfer method. C + + will generate a copy of the MyClass object and pass the copy to the FUN1 function. The member variable A of the MC is modified inside the FUN1 function, which actually modifies the member variable A of the copy, and does not affect the member variable A of the MyClass as the argument.

The FUN2 function uses pointers to MyClass types as arguments. Within this function, the member variable A of the object that the MC points to is modified, which actually modifies the member variable A of the MyClass object.

FUN3 uses a reference to a MyClass object as an argument, which is called a reference. The MC's member variable A is modified inside the function, and as mentioned previously, accessing an object and accessing the object's reference actually accesses the same memory area, so this will directly modify the MyClass member variable A.

As can be seen from the FUN1 and fun3 function bodies, the use of objects and references to objects is the same in syntactic format.

In Fun1, C + + will pass a copy of the argument to the formal parameter. Therefore, if the argument is large in memory, the system overhead in parameter passing will be significant. In Fun2 and FUN3, both the pointer to the argument and the reference to the argument pass the address of the argument to the formal parameter, at best four bytes, and the system overhead is very small.

Three. Returns the referenced function
References also have a useful feature: If a function returns a reference type, then the function can be used as a left value. What is the left value do not understand first, just understand: if an object or expression can be placed on the left of the assignment number, then this object and expression is called the left value.

Cite a useless but illustrative example:
Example four:

Copy Code code as follows:

int i;
int& F1 (int&);
int f2 (int);
F1 (i) = 3;
F2 (i) = 4;

int& F1 (Int&i)
{
return i;
}

int f2 (int i)
{
return i;
}


Try compiling, and you'll find that the 4th sentence is right and the 5th sentence is wrong. For this example, the reference to I is passed to F1, and then F1 returns the reference as it is, and the 4th sentence has the same meaning as i=3.

Check the book, the reference to this feature in the overload operator used more. But I'm still a blur on the overloaded operator, so I can't give an example.
Highlight a small question to see what the following code is wrong:

Copy Code code as follows:

int &f1 ();

F1 () = 5;
...
...
int &f1 ()
{
int i;
int &ri=i;
Return RI;
}

Note the reference Ri returned by the function F1 is declared in the body of the function, and once the function is returned it is beyond the scope of the function, and the area of memory that RI points to is retracted and the memory area occupied by the object I is withdrawn, and then the value of the memory area is lost.

Four. Conversion of references
The examples cited earlier, all types of references are of type int, and these references are initialized to objects bound to type int. So we're assuming that we can declare a reference that has an int type, but is initialized to a float-type object? As shown in the following code:
float F;
int &rv=f;

It turns out that such conversions cannot be compiled by msvc++6.0. But a reference conversion is not entirely impossible, in fact a reference to a base class type can be initialized to bind to a derived class object as long as the two conditions are met:
1, the specified base class is accessible.
2, the conversion is no ambiguity.

For example, example five:

Copy Code code as follows:

Class A
{
Public
int A;
};
Class B:public A
{
Public
int b;
};
A Oa;
B Ob;
a& Mm=ob;
Mm.a=3;

We have a base class A and a derived class B, and we have a base class object, OA and a derived class object OB, and we also declare a reference mm, which has a base class type but is bound to the derived class object ob. Since our two classes are simple enough to satisfy those two conditions, this code is legal. In this example, the base class child object in the mm and the derived class OB is a shared memory unit. Therefore, the statement mm.a=3 is equivalent to ob.a=3, but the expression mm.b is illegal because the base class child object does not include members of the derived class.

Five. Summarize
Finally, give a summary of the reference:
1. References to objects and objects are in a sense a thing, and references to objects and to access objects actually access the same memory area.

2. The use of objects and references to objects is the same in syntax format.

3. The reference must be initialized.

4. After a reference is bound to an object in initialization, it will only bind to that object forever.

5. A reference to a base class type can be bound to a derived class object of that base class, as long as the base class and the derived class meet the two conditions mentioned above. At this point, the reference is actually a reference to the base class child object in the derived class object.

6. When a reference is passed to a function by passing a reference, only the address of the object is passed, and the system consumes less. Accessing a formal parameter in a function body actually accesses the object that is the argument.

7. If a function returns a reference, then the function call expression can be used as the left value.

Six. Other
1. The code in this article is debugged and validated in msvc++6.0.
2. The example in the fourth section, "referencing conversions":
float F;
int &rv=f;

To view the bc++3.1 information, it is said to be legal. At this point the compiler generates a float type of temporary
object, referencing the RV is bound to this temporary object, which means that the RV is not a reference to F. Don't know
What is the use of this trait in the bc++3.1?

3. You can declare such a reference in msvc++6.0:
const INT &rv=3;

The RV's value is 3 at this time and cannot be changed. This may not be of any use. Because if we're going to make
There are more common ways to represent constants with one symbol:
#define RV 3

4. Make a slight change to the example in section Fourth:
float F;
int &rv= (int&) F;

At this time can be compiled by msvc++6.0. At this point the RV is bound to the F, and the RV and F share a storage area. However, since the type of the RV is int, the contents of the store are interpreted as integers when it is accessed through the RV, and the contents of the store are interpreted as real numbers when accessing the storage area through F.

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.