[C++ Drifting] Easily understand the basic syntax and usage of references and their careful implementation

A reference is a data type in C++ that allows us to use an existing variable to create a new name or alias so that the value of the original variable can be accessed and modified through this alias. The essence of a reference is an alias or an alias of a variable.
Insert image description here


basic grammar

A reference in C++ is an alias that allows us to use an existing variable to create a new reference variable. References must be initialized when declared, and once initialized, no other variables can be referenced.

The basic syntax for quoting is as follows:

type &ref = variable;

Among them, type is the type of reference, ref is the name of the reference variable, and variable is an existing variable.

Sample code:

#include <iostream>

int main() {
    
    
    int num = 10;
    int &ref = num;  // 创建一个整型引用ref,引用变量num

    std::cout << "num: " << num << std::endl;  // 输出:num: 10
    std::cout << "ref: " << ref << std::endl;  // 输出:ref: 10

    ref = 20;  // 修改引用变量ref的值,也会修改num的值

    std::cout << "num: " << num << std::endl;  // 输出:num: 20
    std::cout << "ref: " << ref << std::endl;  // 输出:ref: 20

    return 0;
}

In the above example, we created an integer variable num and referenced it using ref. When we modify the value of the reference variable ref, the value of num is also modified. Therefore, the values ​​of num and ref output at the end are both 20.

It should be noted that a reference is just an alias, it does not occupy additional memory space, it just points to an already existing variable. References are very useful in scenarios where functions pass parameters, function return values, avoid copying large objects, etc.


Notes on citations

  1. References must be initialized at declaration time : References must be initialized at declaration time, and once initialized, no other variables can be referenced. For example, int &ref;is wrong and must be written int &ref = num;.

  2. A reference cannot refer to a temporary variable : A reference cannot refer to a temporary variable, that is, the reference cannot be bound to a temporary object. For example, int &ref = 5;is wrong.

  3. References cannot change bound variables : Once a variable is bound by a reference, the bound variable cannot be changed. For example, int num1 = 10; int num2 = 20; int &ref = num1; ref = num2;instead of changing the value of num1 to the value of num2, this code changes the value of num1 to 20.

  4. Note when using references as function parameters : When a reference is passed as a function parameter, modifications to the reference within the function will affect the original variable. This can be used to achieve the effect of a function returning multiple values ​​or modifying the parameters passed in. But it should be noted that if the function parameter is a reference type, the incoming parameter must be a modifiable lvalue, not a constant or temporary variable.

  5. Points to note when references are used as function return values : references can be used as return values ​​of functions, but it should be noted that the returned references cannot point to local variables, because local variables will be destroyed after the function returns. If you return a reference, be sure to return a static variable, a global variable, or memory allocated on the heap via the new operator.


References as function parameters

  1. Returning multiple values ​​through reference parameters: When a function needs to return multiple values, reference parameters can be used. By referencing parameters, a function can store calculation results directly into the parameters passed in, without using the function return value. This avoids creating temporary variables or using pointers to pass results.

For example, the following function returns the sum and difference of two integers by reference to arguments:

void calculateSumAndDifference(int a, int b, int& sum, int& difference) {
    
    
    sum = a + b;
    difference = a - b;
}

int main() {
    
    
    int num1 = 10;
    int num2 = 5;
    int sum, difference;

    calculateSumAndDifference(num1, num2, sum, difference);

    std::cout << "Sum: " << sum << std::endl;  // 输出:Sum: 15
    std::cout << "Difference: " << difference << std::endl;  // 输出:Difference: 5

    return 0;
}
  1. Modify the variable passed in by reference parameter: By reference parameter, the function can modify the value of the variable passed in. This avoids using a pointer to pass the address of a variable and allows you to modify the passed variable directly inside the function.

For example, the following function doubles an incoming integer variable by reference:

void doubleNumber(int& num) {
    
    
    num *= 2;
}

int main() {
    
    
    int num = 10;

    doubleNumber(num);

    std::cout << "Doubled number: " << num << std::endl;  // 输出:Doubled number: 20

    return 0;
}

It should be noted that when a reference is used as a function parameter, the parameter passed in must be a modifiable lvalue, not a constant or temporary variable. Because the reference needs to be bound to an existing variable. If the incoming parameter is a constant or temporary variable, you can use a const reference parameter to receive it to avoid modifying it.

void printValue(const int& num) {
    
    
    std::cout << "Value: " << num << std::endl;
}

int main() {
    
    
    int num = 10;

    printValue(num);  // 输出:Value: 10
    printValue(20);  // 输出:Value: 20

    return 0;
}

In the above example, the printValue function receives a const reference parameter, even if the parameter passed in is a constant or temporary variable, its value can be accessed through the const reference, but its value cannot be modified.


the nature of citations

The essence of a reference is an alias or an alias of a variable. A reference is a data type in C++ that allows us to use an existing variable to create a new name or alias so that the value of the original variable can be accessed and modified through this alias.

In terms of internal implementation, references are usually implemented through pointers, but when using references, we don't need to pay attention to the details of pointers, and we can use references like primitive variables. The compiler automatically handles the underlying pointer manipulation of references.

The nature of citations can be understood through the following characteristics:

  1. References must be initialized at declaration time, and once initialized, the variable to which they are bound cannot be changed. This means that the reference always points to the same variable and cannot be rebound to other variables.

  2. A reference and its bound variable share the same memory space, and they point to the same address. Therefore, the value of a bound variable can be directly accessed and modified by reference.

  3. References can be manipulated like ordinary variables when used, including assignment, passing to functions, and returning values ​​from functions.

  4. References can be passed as function parameters, and can be used to implement functions that return multiple values ​​or modify the effects of incoming parameters.


constant reference

A constant reference is a reference that is bound to a constant object by reference. When a constant reference is declared, the keyword const is used to modify the reference type, indicating that the referenced object is a constant and cannot be modified.

The main characteristics of constant references are:

  1. A constant reference can be bound to a constant object or a non-const object, but the value of the referenced object cannot be modified through a constant reference.

  2. Constant references can be used for function parameters to avoid modification of parameters passed in the function.

  3. Constant references can receive constant objects, non-const objects, and temporary objects.

Here are some examples of constant references:

void printValue(const int& num) {
    
    
    std::cout << "Value: " << num << std::endl;
}

int main() {
    
    
    int num1 = 10;
    const int num2 = 20;

    printValue(num1);  // 输出:Value: 10
    printValue(num2);  // 输出:Value: 20
    printValue(30);    // 输出:Value: 30

    return 0;
}

In the above example, the printValue function receives a constant reference parameter, which can receive constant objects, non-constant objects and temporary objects. Since the parameters are constant references, the values ​​of the parameters passed in cannot be modified inside the function.

The use of constant references in function parameters can avoid modifying the parameters passed in, and can also improve the performance of the program, because constant references do not need to create temporary copies. In addition, constant references can also be used to avoid unnecessary copy operations and improve program efficiency.

Guess you like

Origin blog.csdn.net/Goforyouqp/article/details/132735871