C/C++ const keyword detailed explanation (the most complete in the whole network)

Table of contents

1. const modifies ordinary variables

2. const modified pointer

(1) const modified p:

(2) const modification *p:

(3) const modifies p and *p

4. const modified array

5. const modified function parameters

(1) const modifies ordinary formal parameter variables

(2) const modified pointer parameters

(3) const modified reference parameters

6. const modified function return value

(1) const modifies the return value of a common type

(2) The return value of const modified pointer type    

7, const modified member variables

8, const modified member function


1. const modifies ordinary variables

Modifying ordinary variables with const is actually defining a constant. The following two forms of definition are essentially the same. Its meaning is: the variable value of type TYPE modified by const is immutable. Generally, const variable names are all uppercase.

TYPE const ValueName = value; 

const TYPE ValueName = value;

If we forcibly modify the constant defined by const, an error will be reported.insert image description here

 In fact, although constant variables cannot be modified directly, we can modify constant variables through pointers:

insert image description here

So when the pointer points to a const constant variable, in order to avoid modifying the const constant variable through the pointer, we should use the const pointer to point to the const constant variable accordingly.

const int AMOUNT = 100;
int const *p = &AMOUNT;

What is the role of constants defined with const?

Suppose we often use a number 100 in the code, we can define a constant, let the value of the constant be 100:

const int AMOUNT = 100;

If we don't define a constant, we need to change 100 to 200, and we need to change all 100 that appear in the code to 200 in turn, and if we define a constant, we only need to change the value of the constant variable to 200, which increases Code maintainability.

If const is changed to an external link, the effect is expanded to the global, memory will be allocated during compilation, and initialization may not be performed, it is only used as a declaration, and the compiler thinks that it is defined elsewhere in the program.

extend const int ValueName = value;

2. const modified pointer

(1) const modified p:

int i = 10;
int* const p = &i;

The const modified pointer p means that the pointer cannot be modified, that is, once the address of a variable is obtained, it can no longer point to other variables:

int i = 10;
int * const p = &i;
p++;//p指针指向下一个元素,错误

Although the pointer cannot be modified, the value of the variable pointed to by the pointer can be modified:

int i = 10;
int * const p = &i;
*p = 26;//没问题

(2) const modification *p:

int i = 10;
const int * p = &i;

const modification *p means that the value of the variable it points to cannot be modified through the pointer:

int i = 10;
const int* p = &i;
*p = 26;//通过指针修改其所指变量的值,错误

Although the value of the variable pointed to by the pointer cannot be modified through the pointer, the variable i itself can be changed in any way, such as:

int i = 10;
const int* p = &i;
i=26;
i++;

p can also be changed:

p = &j;

(3) const modifies p and *p

const int* const p;

The const modification of p and *p means that the pointer cannot be changed, and the variable pointed to by the pointer cannot be changed.

Note the following differences:

int i;
const int* p1 = &i;//不能通过指针修改
int const* p2 = &i;//不能通过指针修改
int *const p3 = &i;//指针不能修改
/*判断哪个被const了的标志是const在*的前面还是后面*/

4. const modified array

Array variables are actually const pointers, so they cannot be assigned directly:

int a[]
//a--->int* const a;

The const modified array indicates that each element of the array is const int and cannot be modified, so it must be assigned through initialization, otherwise it cannot be assigned after writing it out.

const int a[]
//a---->const int * const a;

5. const modified function parameters

(1) const modifies ordinary formal parameter variables

void function(const int Var);

This means that the formal parameters will not change, but in fact this is meaningless, because we usually want to ensure that the external actual parameter data does not change, here the formal parameters are actually copies of the actual parameters, and the actual parameters will not change.

(2) const modified pointer parameters

void function(const char* Var);

We assign the address of the external actual parameter to the pointer formal parameter decorated with const, so that we cannot modify the external actual parameter it refers to through the pointer, which protects the security of the data.

But if it is such a const pointer parameter, it is meaningless:

void function(char* const Var);

Because this means that the pointer parameter will not change, but we can still modify the external actual parameter passed through the pointer, and the security of the external data cannot be guaranteed.

(3) const modified reference parameters

void function(const Type& Var); //引用参数在函数内不可以改变

The parameter is a reference, and the external actual parameter is passed to the reference formal parameter, and the external actual parameter itself is passed without copying, which increases efficiency. At the same time, the parameter is a const reference, and the actual parameter cannot be modified by reference, ensuring the security of the external data .

Note:

If the function parameter is a non-const reference/pointer, it cannot receive a const variable (address), because it will cause the authority to be enlarged and an error will be reported. It can only receive a non-const variable (address), and if the function parameter is a const reference/ Pointer, it can receive both const variables (addresses) and non-const variables (addresses), which is the reduction of permissions, no problem, if the function is a const ordinary variable, then it can receive const variables or non-const variables Variable, because it will not cause the amplification of permissions.

6. const modified function return value

The return value of the const modified function is not very practical.

(1) const modifies the return value of a common type

const int fun1();

This is actually meaningless, because what is returned is actually a temporary variable, and the temporary variable itself is constant.

(2) The return value of const modified pointer type    

The first case is const modified *p:

const int * fun2();
const int *p = fun2();//调用正常
int* p2 = fun2();//调用失败

Here is a brief analysis of the reason for the failure of the third code call, because fun2() is actually a const int* pointer, we cannot modify the variable it refers to through the pointer, and after assigning the const int* pointer of fun2() to p2 , p2 is a non-const pointer, and the variable pointed to by it can be modified through the pointer, which causes the access right of the variable pointed to by the pointer to be enlarged, so the call fails.

The second case is that const modifies p

int* const fun3();
int * const p = fun3();//调用正常
int *p2 = fun3();//调用正常 

Look at the third sentence of code, why in this case, can the returned int* const pointer be assigned to a non-const pointer?

We can regard fun3() as an int * const pointer. Although the pointer cannot be modified, we can modify the variable it refers to through the pointer. After assigning it to p2, we can still modify the variable it refers to through the pointer. The access rights of the variable pointed to by the pointer have not changed, so of course there is no problem with such assignment.

7, const modified member variables

The member variable of the const modified class represents a member constant and cannot be modified, and it can only be assigned in the initialization list.   

 class A

    { 

        …

        const int nValue;//成员常量不能被修改

        …

        A(int x): nValue(x) { };//只能在初始化列表中赋值

     } 

8, const modified member function

The "member function" modified by const is called const member function. The type of this pointer is: class type * const this, that is, in the member function, the this pointer cannot be modified, but the member variable of the object pointed to by it can be modified. The const modified class member function actually limits this to: const class Type * const this, indicating that any member of the calling object cannot be modified in this member function, which protects the object.

Format: Put the const keyword after the parentheses of the function

class Date
{
public:
    void Display()const
    {
        cout<<_year<<endl;
    }
    //该成员函数实际上是这样
    /*
    void Display(const Date *const this)
    {
        cout<<this->_year<<endl;
    }*/
private:
    int _year;
    int _month;
    int _day;
};

Regarding const member functions, the following points need our attention:

  1. Just like declaring references and pointers in function parameters as const as much as possible, as long as the member function does not modify the calling object, it should be declared as const, which can prevent the calling object from being modified, and ordinary objects and const objects All can be called (will not cause amplification of read and write permissions).
  2. As mentioned earlier, read and write permissions can only be reduced, not enlarged. Therefore, const objects can only call const member functions, and non-const member functions cannot be called, because const objects cannot be modified. If a const object calls a non-const member function , non-const member functions can modify the const object that calls it, which is the amplification of permissions and will report an error. A non-const object can call a non-const member function, or a const member function, because this is a narrowing of permissions.
  3. If the member function of a class is modified by const, the member function cannot call any non-const member function in the class, because the non-const member function may modify the const object, causing the amplification of permissions.
  4. A const member function can access an object's const members, but other member functions cannot.

The above is my understanding of the role of the const keyword. Due to the limited level, there are inevitably some defects in the content. Welcome to criticize and correct...

·       

·            

Guess you like

Origin blog.csdn.net/weixin_44049823/article/details/128735316