Reference in C ++ (zz)

Source: Internet
Author: User

1. Introduction

References are new language features introduced by C ++. In terms of semantics, reference is the alias of a variable, just like the "word" and "Number" of ancient people. Dongpo jushi and Su Shi are just different names of a person. The impact of referenced operations on variables is exactly the same as that of direct operations on variables. For example:

Int I = 0;

Int & iRef = I;

IRef ++; // I = iRef = 1

Although the reference does not use the pointer operator (*,->), it seems to be no different from the pointer, and in the above example, the function of this reference can be completely done by the pointer. So why does C ++ add such a feature? The reference should obviously have a function that cannot be completed by the pointer, otherwise it will lose its value. We will leave this discussion in section 3rd.

2. referenced syntax

Here we will only discuss some syntax-related issues.

· The reference must be initialized at the same time as the definition.

Int I;

Int & j; // error, not initialized.

Int & k = I; // correct

In this example, there is a good analogy. When a child is a child, the child starts an "outer Number". These outer numbers always mean something when they are generated, that is, for a specific child. The same is true for references. when defining a definition, you must specify its alias.

· The external (extern) reference definition does not need to provide the initial value

Extern int & I; // correct, no initial value required

· The reference cannot be referenced by other variables after initialization.

Int j, k;

Int & I = j;

I = k; // error, cannot be changed!

Reference is similar to a constant pointer (int * const P). You cannot modify the reference point.

· Referenced address

Suppose the following is the definition:

Int J;

Int & I = J;

So what should I be? Is it a "referenced address? The answer is: no. & I = & J, which is the address of the variable J.

3. Reference Usage tips

3.1 references and Polymorphism

References are another method that can produce polymorphism effects except pointers. This means that a base class reference can point to its derived class instance. For example:

Class;

Class B: public

{

...

};

  

B;

A & Aref = B; // The base class references a derived class.

If a virtual function is defined in Class A and this virtual function is rewritten in Class B, Aref can be used to produce polymorphism.

3.2 As A PARAMETER

An important function of reference is to act as the parameter type of a function. C/C ++ function parameters are passed values. If a large object (such as a large structure) needs to be passed as parameters, the previous (in C) the solution is usually a pointer, because this can avoid putting all the objects on the stack and improve the program efficiency. But now (c ++) has added a more efficient option, that is, reference.

Like pointer-type parameters, when a reference is passed as a parameter, no matter what type of object is pointed to, only four bytes of the stack are pressed (on a 32-bit machine ). The size of the 4-byte referenced is determined based on the code generated by the compiler, because sizeof (a_reference) can only obtain the size of the object it points.

When the referenced parameter can be defined as const, it should be defined as const as much as possible. This is not just to make the code more robust, but also has some other needs, for example, assume that the following function declaration is available:

String Foo ();

Void bar (string & S );

The following expression is invalid:

Bar (FOO ());

Bar ("Hello World ");

The reason is that both the Foo () and "Hello World" strings generate a temporary object. In C ++, these temporary objects are of the const type. Therefore, the above expression tries to convert a const type object to a non-const type, which is invalid.
3.3 As Return Value

When a reference is returned, some rules must be followed. These rules include:

Local variables cannot be referenced. For details, refer to item 31 of Objective C ++ [1. The main reason is that local variables will be destroyed after the function returns. Therefore, the returned reference becomes a reference with "no finger" and the program enters the unknown state.

You cannot return a reference to the memory allocated by the new function. For details, refer to item 31 of Objective C ++ [1. Although there is no passive destruction of local variables, this situation (returning a reference to the memory allocated by the new function) faces other embarrassing situations. For example, if a reference returned by a function only appears as a temporary variable and is not assigned to an actual variable, the space pointed to by the reference (allocated by new) cannot be released, cause memory leak.

You can return a reference to a class member, but it is best to use Const. This principle can be referred to item 30 of Objective C ++ [1. The main reason is that when an object attribute is associated with a business rule, its value assignment is often related to some other attributes or the state of the object, therefore, it is necessary to encapsulate the value assignment operation in a business rule. If other objects can obtain the non-constant reference (or pointer) of this attribute, a simple value assignment to this attribute will damage the integrity of business rules.

In addition, references are often related to some Operator Overloading:

Stream operator <and>. These two operators are often used consecutively, for example, cout <"hello" <endl; therefore, the return value of these two operators should be a stream reference that still supports these two operators. Other optional solutions include returning a stream object and returning a stream object pointer. However, for a returned Stream object, the program must re-(copy) to construct a new stream object. That is to say, two consecutive <operators are actually for different objects! This is unacceptable. If a stream pointer is returned, the <operator cannot be used consecutively. Therefore, returning a stream object reference is the only choice. This unique choice is critical. It illustrates the importance of reference and is irreplaceable. Maybe this is why the concept is introduced in C ++.

Value assignment operator =. This operator can be used continuously like a stream operator, for example, x = j = 10; or (x = 10) = 100; the return value of the value assignment operator must be a left value, so that the value can be assigned. Therefore, it is referenced as the unique return value choice of this operator.

In other operators, reference cannot be returned:

+-*/Arithmetic Operators. They cannot return references. The Objective C ++ [1] Item23 discusses this issue in detail. The main reason is that these four operators do not have side effect. Therefore, they must construct an object as the return value. Optional solutions include: 1. Return an object; 2. Return a reference to a local variable, 3. Return the reference of a new allocated object. 4. Return the reference of a static object. According to the preceding three rules that reference the returned value, both the 2nd and 3 schemes are rejected. Static object reference is caused by errors because (a + B) = (c + d) is always true. Therefore, only one object is returned.

3.4 when to use references

● Now we can summarize the question of when to use references. First, we need to see when reference must be used:

Stream operator <and>, operator =, [], front ++ --, unary operator * (which requires the return of the Left value) Return Value

Copy the parameters of the constructor (otherwise, recursive calling will be formed) and the value assignment operator = parameter ()

● References are recommended in other cases, but they can also be left blank. If you do not want to use references, you can replace them with pointers or other similar things:

Parameter table of exception catch

Passing large objects as parameters

Returns a single element in the container class.

Returned class data member (non-built-in data type member)

Returns other persistent objects that are not destroyed by the winner.

● In other cases, references cannot be returned:

+-*/Four Arithmetic Operators

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.