• References are in C++, not in C.
    • 引用的概念只在C++中
  • A reference is an alias to an already-existing variable/object.
    • 引用是一个已存的变量或者对象的别名 ```cpp

      include

      using namespace std;

int main() { int num = 0; int &num_ref = num; // &放在类型的后面 代表后面定义的变量是引用,而不是取地址 cout << “num = “ << num << endl;

  1. num_ref = 10;
  2. cout << "num = " << num << endl;
  3. return 0;

} // num = 0 // num = 10

通过上例子,无论是num还是num_ref,它们两个对应同样的数据,

- A reference to an object
   - 对象的引用
```cpp
struct Matrix
{
    int rows;
    int cols;
    float * pData;
};
Matrix matA = {3,4};
matA.pData = new float[matA.rows * matA.cols]{};

Matrix & matA_ref = matA; // matA_ref 是matA的引用

Matrix * pMatA = &matA; // pMatA指向的是matA的首地址

:::warning A reference must be initialized after its declaration. :::

int & num_ref; // error 
Matrix & mat_ref; // error

Reference VS Pointer: References are much safer。
对于指针,需要时刻小心是否发生越界,而引用在被声明出来,必须要初始化,一定会指向一个具体的对象。

  • Function parameters with a huge structure
  • If the huge struct is passed as a function parameter
    • 提到上一节的问题,如果需要传递一个超大的结构体给函数,怎么办 ```cpp struct PersonInfo { char firstname[256]; char middlename[256]; char lastname[256]; char address[256]; char nationalID[16]; // and more };

char * fullname(struct PersonInfo pi) { // … }

上述代码还是按照6.2节,按值进行传参,需要把该结构体拷贝给函数,The data will be copied. Not a good choice!

- One solution is to use a **pointer**
```cpp
struct PersonInfo
{
    char firstname[256];
    char middlename[256];
    char lastname[256];
    char address[256];
    char nationalID[16];
     // and more
};

char * fullname(struct PersonInfo * ppi)
{
    // 如果使用了指针进行传参,在对该数据进行操作之前,
    // 必须要进行一系列严谨的对指针进行检查
    if (ppi == NULL)
    {
        cerr << "Invalid pointer" << endl;
        return NULL;
    }
    // ...
}
  • References as function parameters
    • No data copying in the reference version; Better efficiency
    • The modification to a reference will affect the original object | image.png | image.png | | —- | —- |

:::warning 如果传递给参数的引用数据被修改,那么函数外部的数据也会被修改;因为他们指向了同一地址 ::: To avoid the data is modified by mistakes, 可以在struct前加上const,就不会改变引用数据的值了。

float matrix_max(const struct Matrix & mat)
{
    float max = FLT_MIN;
    // ...
    return max;
}