Introducing C++ References and Comparing Pointers

Reprinted from: https://blog.csdn.net/xiao__tian__/article/details/51814617

References in C++:

A reference introduces a synonym for an object. Defining a reference is represented in a similar way to defining a pointer, except that & replaces *. Reference is an important extension of C++ to the C language. reference is a

An alias for a variable (target) that operates on a reference exactly as it does on the variable directly. The format is: type & reference variable name = defined variable name.

Citation Features:

①A variable can take multiple aliases.

②The reference must be initialized.

③ The reference can only be referenced once at the time of initialization, and cannot be changed to refer to other variables instead.



①Basic reference:

  1. void TestReference1 ()  
  2. {  
  3.      int a = 1;  
  4.      int& b = a;  
  5.   
  6.      cout<<"a:address->" <<&a<< endl;  
  7.      cout<<"b:address->" <<&b<< endl;  
  8.   
  9.      a = 2;  
  10.      b = 3;  
  11.      int & c = b; // refer to a reference variable, an alias of an alias  
  12.      c = 4;  
  13. }  



②const reference:
  1. void TestReference2 ()  
  2. {  
  3.      int d1 = 4;  
  4.      constint & d2 = d1;   
  5.      d1 = 5; //When d1 changes, the value of d2 also changes.  
  6.      //d2 = 6;//Cannot assign values ​​to constants (quantities that cannot be modified).  
  7.   
  8.      const int  d3 = 1;   
  9.      constint & d4 = d3;   
  10.      //int&d5 = d3;  
  11.      const int  & d6 = 5; //Constants are constant, only constant references can refer to constants   
  12.   
  13.      double d7 = 1.1;  
  14.      //int& d8 = d7;//d7 is double type, d8 is int, and a temporary variable is generated when d7 is assigned to d8  
  15.                    //That is to say, d8 refers to this temporary variable with constant, so it cannot be assigned.  
  16.      constint& d9 = d7;   
  17. }  


③ Quote as a parameter:

  1. 1. [Pass by value] If the formal parameter is a non-reference pass-by-value method, a local temporary variable is generated to receive the value of the actual parameter  
  2. void  Swap ( int  left,  int  right)  //The way of value transfer cannot achieve exchange, because when passing parameters, a temporary copy is copied for the parameters left and right, and the copy value is exchanged, because it is a temporary variable function exit, the variable pin { //Destruction will not affect the values ​​of external left and right.  
  3.      int temp = left;  
  4.      left = right ;  
  5.      right = temp ;  
  6. }  
  7.   
  8. 2. [Pass by reference] If the formal parameter is a reference type, the formal parameter is an alias of the actual parameter.  
  9. void  Swap ( int & left,  int & right) //If a reference is used, no temporary copy is made. The usage of & here is just another name of the original parameter, so when modifying, modify the variable value directly on the basis of the original parameter.  
  10. {  
  11.      int temp = left;  
  12.      right = left ;  
  13.      left = temp ;  
  14. }  
  15.   
  16. 3.【Pointer passing】  
  17. void  Swap ( int * pLeft,  int * pRight) //The address is passed in, because the address is unique, so the pointer can modify its content by accessing the address.  
  18. {  
  19.      int temp = *pLeft;  
  20.      *pLeft = *pRight;  
  21.      *pRight = temp;  
  22. }  



Although it is convenient to quote, use with caution:

(1) & here is not for address operation, but for identification.

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

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

(4) After the reference is declared, the target variable name has two names, namely the original name of the target and the reference name, and the reference name can no longer be used as an alias for other variable names.

(5) To find the address of the reference is to find the address of the target variable. That is, the reference name is an alias for the target variable name. A reference by definition means that a reference does not occupy any memory space, but the compiler will

It is implemented as a const pointer, that is, a pointer to an immutable position, so the reference actually occupies the same memory as a normal pointer.

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

(7) Common uses of reference: as a parameter of a function, the return value of a function.



Summarize:

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

2. If the returned object still exists outside the scope of the current function, it is better to return by reference because it is more efficient.

* Differences and connections between references and pointers (
hot spots in the written test
)

1. A reference can only be initialized once at the time of definition, and it cannot be changed to point to other variables afterward (from one to the end); the value of a pointer variable is variable.

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

3. The meaning of sizeof pointer object and reference object is different. The sizeof reference is the size of the variable pointed to, and the sizeof pointer is the size of the object address.

4. Pointer and reference increment (++) and decrement (--) have different meanings.

5. Relatively speaking, references are safer than pointers.


Pointers are more flexible than references, but they are also risky. When using a pointer, be sure to check whether the pointer is NULL, and it is best to set the pointer after space reclamation.

Zero to avoid problems such as memory leaks.




Ⅰ. Differences and connections between references and pointers:

Differences :

1. A pointer is an entity, and a reference is just an alias;

 2. There is no need to dereference (*) when using the reference, and the pointer needs to be dereferenced;

 3. A reference can only be initialized once when it is defined, and is immutable after that; a pointer is mutable;

 4. 引用没有 const,指针有 const;const修饰的指针不可变;

 5. 引用不能为空,指针可以为空;

 6. “sizeof 引用”得到的是所指向的变量(对象)的大小,而“sizeof 指针”得到的是指针本身(所指向的变量或对象的地址)的大小;

7. 指针和引用的自增(++)运算意义不一样;

 8.从内存分配上看:程序为指针变量分配内存区域,而引用不需要分配内存区域。

★相同点两者都是地址的概念,指针指向一块儿内存,其内容为所指内存的地址;引用是某块儿内存的别名。





Ⅱ.const在C和C++中的含义(笔试热点):

⑴C中的const,功能比较单一,较容易理解
作用:被修饰的内容不可更改。
使用场合:修饰变量,函数参数,返回值等。(c++中应用场合要丰富的多)
特点: 是运行时const,因此不能取代#define用于成为数组长度等需要编译时常量的情况。同时因为是运行时const,可以只定义而不初始化,而在运行时初始化。如 const int iConst;。 另外,在c中,const变量默认是外部链接,因此在不同的编译单元中如果有同名const变量,会引发命名冲突,编译时报错。
⑵c++中的const:

a、非类成员const:

①const变量默认是内部连接的,因此在不同的编译单元中可以有同名的const 变量定义。

②编译时常量,因此可以像#define一样使用,而且因为上面一点,可以在头文件中定义const变量,包含的不同的cpp文件(编译

单元)中使用而不引起命名冲突。

③ The compiler does not allocate memory for const variables by default, unless: 1. Use extern to declare, 2: There is an address that refers to the const variable in the program.

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

b. const in the class:

①Same as const in C language, it is only a runtime constant and cannot be used as an array dimension, that is, it cannot replace #define. Use the following two ways to replace #define in the class: 1: static  const... 

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

②The const variable in the class occupies storage space.

③ The const member variables in the class need to be initialized in the constructor initialization list.

④const object: During the life cycle of the object, it must be ensured that no member variables are changed. A const object can only call const member functions.

⑤const member function: void fun() const ... can be called not only by const objects, but also by non-const objects. Therefore, if it is confirmed that any member function does not change

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

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324738838&siteId=291194637
Recommended