When to use references, pointers, and pass by value

Source: Internet
Author: User

Question:

1. When a class object is passed as a real parameter, what is the difference between passing a value and passing a reference?
For example: datetype examplefun (cstring & strfilename,...) and
Datetype examplefun (cstring strfilename ,...)

Before answering the questions, let's take a look at two basic concepts: form parameters and real parameters.

-> In general, the form parameter and the real parameter are the actual parameters;
-> For details, the form parameter is only an abstract description of the real parameter, but declares the type of real parameter that a function (method) can accept, we are not sure what the actual content of the accepted arguments is;

The real parameter is the specific content (value) of the parameter corresponding to the function (method), and the initial meaning (content) of the form parameter is determined by the real parameter. the parameter is released after the function (method) is returned.


Enter the topic: parameter transmission method:Transfer Value and address;
1. the value passing method only transfers the copy of the real parameter value to the function (method) and operates the form parameter in the method. The object is the copy of the real parameter, which cannot affect the real parameter. after the method is returned, the form parameter is released and discarded, and the content of the real parameter is not changed;

2. the address transfer method transmits the address of the real parameter to the function (method). The operation on the form parameter in the method is equivalent to the same operation on the real parameter. After the return method ends, the parameters are also released. The content of the parameters is the result of the operation on the parameters.

The address transfer method can be subdivided:Pass-by-reference and pass-by-pointer)

A reference is actually an object alias. It is used to pass an object's address as a parameter, rather than the object itself.

This is the answer to the previous question: transferring a reference avoids a copy of a real parameter to a form parameter, improving the efficiency.

Reasons for using referenced parameters:

1. the programmer can modify the data objects in the call function.

2. Transferring references instead of the entire data object can speed up program running.

When the data object is large (such as structure and Class Object), the second reason is the most important, which is also the reason for using pointer parameters. This makes sense, because the reference parameter is actually another interface of pointer-based code.

 

So when to use references and when to use pointers? When should it be passed by value? The following are some guiding principles:

For functions that use passed values without modification:

1. If the data object is small, such as the built-in data type or small structure, it is passed by value.

2. If the data object is an array, use a pointer because it is the only choice and declares the pointer as a pointer to the const.

3. If the data object is of a large structure, use the const pointer or const reference to improve the running efficiency. This saves the time and space required for the replication structure.

4. If the data object is a class object, use const reference. The semantics of class design often requires reference, which is the main reason why C ++ adds the reference feature. Therefore, the standard way to pass object parameters is to pass parameters by reference.

For a function that modifies the data in a call function:

1. If the data object is of the built-in data type, a pointer is used. If you see Code such as Fixit (& X) (where X is int type), it is obvious that this function will modify X.

2. If the data object is an array, only pointers can be used.

3. If the data object is a structure, a reference or pointer is used.

4.If the data object is a class object, reference is used.

Of course, this is just some guiding principles, and there are likely to be good reasons to make other choices. For example, for the basic type, CIN uses reference. Therefore, you can use CIN> N instead of CIN> & N.

 

 

 

 

 

Other materials have been found:

1.

What is "reference "? What should I pay attention to when declaring and using "reference?

A reference is the "alias" (alias) of a target variable. operations on an application are identical to operations on a variable.

When declaring a reference, remember to initialize it. After the reference declaration is complete, the target variable name has two names, that is, the original name and reference name of the target, and the reference name cannot be used as the alias of other variable names. Declaring a reference is not a new variable. It only indicates that the reference name is an alias of the target variable name. It is not a data type, so the reference itself does not occupy the storage unit, the system does not allocate storage units to references. You cannot create an array reference.

Will call the copy constructor and destructor

A A () {...; return * This ;}
A & A () {...; return * This ;}
The copy constructor and destructor are not called.
It should all be used as the left value.

When a variable is returned, a copy is generated. When a reference is returned, it will not be copied. You can regard the reference as an alias of a variable, that is, other names. The referenced and referenced variables are actually one thing, there are only two names.

The key to the problem is that when you want to return a reference instead of a copy, you must ensure the validity of the reference, such:
Int & fun () {int A; A = 10; return ;}
This is not acceptable, because a will be destroyed when fun exits, and the reference of a returned is invalid.
In this case, if the return type of fun is not Int & but int, there is no problem.

Therefore, to return a reference, the "Temporary Variable" cannot be "temporary". At least it must be destroyed after the reference is used outside the function.

2. Benefits of returning a reference:

1) passing a reference to a function has the same effect as passing a pointer. In this case, the parameter of the called function becomes an actual parameter variable or an alias of the object in the original main function, therefore, the operations on the parameters in the called function are the operations on the corresponding target object (in the main function.

(2) using the reference parameter to pass the function does not generate a copy of the real parameter in the memory, it is directly to operate on the real parameter; while using the general variable to pass the function parameter, when a function call occurs, you need to allocate storage units to the parameters. The parameters are copies of the real variables. if the object is passed, the copy constructor will also be called. Therefore, when the data transmitted by a parameter is large, it is better to use reference than to transmit a parameter using a common variable.

(3) Although using pointers as function parameters can achieve the same effect as using references, in the called function, storage units must be allocated to the parameters, the "* pointer variable name" format must be used repeatedly for calculation, which can easily lead to errors and the program reading is poor. On the other hand, at the call point of the main function, the variable address must be used as the real parameter. References are easier to use and clearer.

3. When do I need to use "regular reference "?

If you want to improve program efficiency by referencing, and protect the data transmitted to the function from being changed in the function, you should useRegular reference. Common Reference declaration method: const type identifier & reference name = target variable name;

Example 1

Int;

Const Int & RA =;

Ra = 1; // Error

A = 1; // correct

Example 2

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.

The referenced parameter should be defined as const if it can be defined as Const.

4. Use "Reference" as the format, benefits, and rules of the function return value type?

Format: type identifier & function name (parameter list and type description) {// function body}

Benefit: do not generate a copy of the returned value in the memory. (Note: For this reason, it is not advisable to return a reference to a local variable. As the survival of the local variable ends, the corresponding reference will also become invalid, resulting in a runtime error!

Note:

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

(2) 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.

(3) 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.

(4) The function of declaring the returned value of stream operator overload as "Reference:

Stream operators <and>, which 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 only return value choice of this operator.

Example 3

# Include <iostream. h>

Int & put (int n );

Int Vals [10];

Int error =-1;

Void main ()

{

Put (0) = 10; // use the put (0) function value as the left value, equivalent to Vals [0] = 10;

Put (9) = 20; // use the put (9) function value as the left value, which is equivalent to Vals [9] = 20;

Cout <Vals [0];

Cout <Vals [9];

}

Int & put (int n)

{

If (n> = 0 & n <= 9) return Vals [N];

Else {cout <"subscript error"; Return Error ;}

}

(5) In some other operators, the reference cannot be returned.: +-*/Arithmetic operator. 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: returning an object and returning a reference to a local variable, returns the reference of a newly assigned object and a static object reference. 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.

5. What is the relationship between "reference" 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.

Example 4

Class A; Class B: Class A {...}; B; A & ref = B;

6. What is the difference between "reference" and pointer?

After a pointer variable points to an object, it indirectly operates on the variable it points. When pointers are used in a program, the program has poor readability. The reference itself is the alias of the target variable, and the reference operation is the operation of the target variable. In addition, it is the difference between the ref passed to the function and the pointer mentioned above.

7. When do I need to "Reference "?

Stream operators <and>, return values of the value assignment operator =, parameters of the copy constructor, parameters of the value assignment operator =, and references are recommended in other cases.

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.