C + + Reference to the detailed __c++

Source: Internet
Author: User
Tags constant

references in C + +:

References introduce a synonym for an object. The presentation of the definition reference is similar to the definition pointer, except that the * is replaced with &. The reference (reference) is an important extension of C + + to the C. language. A reference is a

An alias for a variable (target) that is identical to the operation of the reference to the direct manipulation of the variable. The format is: type & reference variable name = variable name that has already been defined.

The characteristics of the reference:

① A variable is preferable to multiple aliases.

The ② reference must be initialized.

③ references can only be referenced once at initialization time and cannot be changed to refer to other variables instead.



① Base reference:

void TestReference1 ()
{
     int a = 1;
     int& B = A;

     cout<< "a:address->" <<&a<< Endl;
     cout<< "b:address->" <<&b<< Endl;

     A = 2;
     b = 3;
     int& C = b;//references a reference variable, alias alias
     C = 4;
}



②const Reference:

void TestReference2 ()
{
     int d1 = 4;
     const int & d2 = D1;
     D1 = 5;//d1 Change, d2 value will also change.
     //D2 = 6;//cannot assign a value to a constant (a quantity that cannot be modified).

     const int d3 = 1;
     const int & d4 = D3;
     INT&D5 = D3;
     const int & d6 = 5;//constants have constancy, and only regular references can refer to constant

     double d7 = 1.1;
     int& D8 = D7;//d7 is a double type, D8 is to generate a temporary variable when INT,D7 is assigned to D8
                   //That is, the D8 refers to this temporary variable with constancy, so it cannot be assigned a value.
     const int& D9 = D7;
}


③ Reference as parameter:

1. "Value delivery" if the parameter is not a reference value method, the generated local temporary variable receives the argument's value
void swap (int left, int right)/value passed in a way that cannot be exchanged because a temporary copy of the parameter left and right is copied when the argument is passed. The exchange is the replica value, because it is a temporary variable function exit, the variable pins {                                //destroyed, and will not affect the external left and right values.
     int temp = left;
     left = right;
     right = temp;
}

2. "Reference delivery" if the formal parameter is a reference type, then the formal parameter is an alias for the argument.
void Swap (int& left, int& right)//use references, do not make temporary copy,& use instructions here is just another name of the original parameter, so modify the original parameter directly on the basis of the variable value.
{
     int temp = left;
     right = left;
     left = temp;
}

3. "Pointer pass"
void Swap (int* pleft, int* pright)//The address is passed in, because the address is unique, so the pointer can then modify its contents by accessing the address.
{
     int temp = *pleft;
     *pleft = *pright;
     *pright = temp;
}



the reference is convenient and must be used with caution:

(1) & here is not to find the address operation, but to play the role of identification.

(2) The type identifier refers to the type of the target variable.

(3) When declaring a reference, it must be initialized at the same time.

(4) after the declaration of the reference, the equivalent of the target variable name has two names, that is, the target's original name and reference name, and can no longer be used as an alias for other variable names.

(5) to address the reference, that is, the target variable to find the address. That is, the reference name is an alias to the target variable name. References are defined to say that a reference does not occupy any memory space, but the compiler typically

is actually a const pointer, a pointer to an immutable position, so the reference actually occupies the same memory as the generic pointer.

(6) An array of references cannot be established. Because an array is a collection of several elements, you cannot establish a collection of references, but you can establish a reference to an array.

(7) Reference common usage: As a function parameter, function return value.



Summary:

1. Do not return a reference to a temporary variable.

2. If the return object is out of scope for the current function, it is best to return with the reference because it is more efficient.

* References and pointers to the differences and links (written hot)

1. References can only be initialized once at the time of definition and cannot be changed to point to other variables (one-woman), and the values of pointer variables are variable.

2. The reference must point to a valid variable and the pointer can be empty.

3. SizeOf pointer objects and reference objects have different meanings. The sizeof reference gets the size of the variable being pointed to, and the sizeof pointer is the size of the object's address.

4. Pointers and citations (+ +) self-subtraction (-) have different meanings.

5. In contrast, references are more secure than pointers.


pointers are more flexible than references, but they are risky. Be sure to check that the pointer is empty (NULL) when using the pointer, and that the pointer is best placed after the space is recycled

0, lest the occurrence of the wild pointer caused by memory leakage leaks and other problems .




Ⅰ. Differences and links between references and pointers:

★ Different points :

1. The pointer is an entity and the reference is only an individual name;

2. References need not be referenced (*), the pointer needs to dereference;

3. References can only be initialized once at the time of definition, and then immutable, and the pointer is variable;

4. The reference does not have a const, the pointer has const;const modification of the pointer is immutable;

5. The reference cannot be null, the pointer can be empty;

6. The "sizeof reference" obtains the size of the variable (object) to which it is pointed, and the "sizeof pointer" gets the size of the pointer itself (the address of the variable or object to which it is directed);

7. The pointer and the reference of the self-increase (+ +) operation is not the same meaning;

8. See from memory allocation: The program allocates memory areas for pointer variables, and references do not need to allocate memory regions.

★ The same point : Both are the concept of the address, the pointer points to a memory, its content is the address of the memory, refers to a block of memory alias.





The meaning of ⅱ.const in C and C + + (written hot):

⑴c in the const, the function is relatively single, easier to understand :
function: The content that is decorated cannot be changed.
usage: modifier variables, function parameters, return values, and so on. (c + + in the application of the situation is much richer)
Features: runtime const, and therefore cannot replace #define used to become the length of the array, such as the need to compile a constant amount of time. Also, because it is run-time const, it can be defined, not initialized, and initialized at run time. such as const int iconst;. In addition, in C, the const variable defaults to an external link, so if you have a const variable with the same name in a different compilation unit, a naming conflict is raised, and the compilation times is wrong.
Const in ⑵c++:

A, non-class member Const:

The ①const variable is internally connected by default, so you can have a const variable definition with the same name in a different compilation unit.

② compile-time, so it can be used like #define, and because of the above, you can define the const variable in the header file, including the different CPP files (compiled

unit) without causing a naming conflict.

The ③ compiler does not allocate memory for the const variable by default, unless: 1. using extern declaration, 2: There is an address in the program that references the const variable.

Temporary objects/built-in variables in ④c++ have the const attribute by default.

B, the const in the class:

①, like the const in C, is just a regular operation and cannot be used as an array dimension, that is, it cannot replace #define. Use the following two methods in the class to replace the #define:1:static const ...

2:enum{...} An enum does not occupy storage space.

The const variable in the ② class occupies storage space.

The const member variable in the ③ class needs to be initialized in the constructor initialization list.

④const object: Within the object lifecycle, no member variables must be guaranteed to be changed. The const object can only invoke const member functions.

⑤const member function: void fun () const ... Can be invoked not only by a const object, but also by a non-const object, so if you confirm that any member function does not change

Change any member variable, you should habitually define the function as a const type.

⑥ if an object is defined as a const, then the Const object "may" be put into ROM, which is sometimes very important in embedded development.



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.