C++ const summary

const is the abbreviation of constant, the original meaning is unchanged, not easy to change. In C++, it is used to modify built-in type variables, custom objects, member functions, return values, and function parameters.

C++ const allows you to specify a semantic constraint, and the compiler enforces this constraint, allowing the programmer to tell the compiler that a certain value remains unchanged. If a certain value does remain unchanged in programming, you should explicitly use const, so you can get the help of the compiler.

One, const modifies common types of variables

const int  a = 7; 
int b = a; // correct
a = 8; // error, cannot be changed

a is defined as a constant, and a can be assigned to b, but a can not be assigned again. It is illegal to assign a value to a constant, because a is considered a constant by the compiler and its value cannot be modified.

Then look at the following operations:

Instance

#include
 
using namespace std;
 
int main(void)
{
    const int  a = 7;
    int  *p = (int*)&a;
    *p = 8;
    cost <

For const variable a, we take the address of the variable and assign it to the pointer to int, and then use *p = 8; to re-assign the value in the address of variable a, and then output the value of a.

You can see from the debug window below that the value of a has been changed to 8, but the output result is still 7.
C++ const summary C++ const summary
C++ const summary C++ const summary
From the results, we can see that the compiler then thinks that the value of a is 7, which was defined at the beginning, so the operation on const a will produce the above situation. So don't try to assign values ​​to const variables lightly, as this will produce unexpected behavior.

If you don't want the compiler to be aware of the above operations on const, we can add the volatile keyword in front of const.

The Volatile keyword corresponds to the opposite of const, which is changeable and easy to change. So it will not be optimized by the compiler, and the compiler will not change the operation of the a variable.

Instance

#include
 
using namespace std;
 
int main(void)
{
    volatile const int  a = 7;
    int  *p = (int*)&a;
    *p = 8;
    cost <

The output is 8 as we expect.
C++ const summary C++ const summary

Two, const modified pointer variable

const modified pointer variable has the following three cases.

  1. A: const modifies the content pointed to by the pointer, the content is invariable.
    B: const modifies the pointer, the pointer is not variable.
    C: const modifies the pointer and the contents pointed to by the pointer, the pointer and the contents pointed to by the pointer are not variable.

For A:

const int *p = 8;

The content 8 pointed to by the pointer cannot be changed. Referred to as left definite value, because const is located to the left of the * sign.

For B:

int a = 8;
int* const p = &a;
*p = 9; // correct
int  b = 7;
p = &b; // error

For const pointer p, the memory address pointed to cannot be changed, but its content can be changed. Abbreviated, right-oriented. Because const is located to the right of the * sign.

For C: it is a combination of A and B

int a = 8;
const int * const  p = &a;

At this time, the content pointed to by const p and the memory address pointed to have been fixed and cannot be changed.

For the three cases of A, B, and C, according to the position of const in the *, I summarize three sentences that are easy to remember: "left fixed value, right directed, const modifies invariants".

Three, const parameter transfer and function return value

There are three cases for const modified function parameters.

A: The const modification of value transfer is passed. Generally, const modification is not needed in this case, because the function will automatically generate temporary variables to copy the actual parameter value.

Instance

#include
 
using namespace std;
 
void Cpf(const int a)
{
    cost <

B: When the const parameter is a pointer, it can prevent the pointer from being accidentally tampered with.

Instance

#include
 
using namespace std;
 
void Cpf(int *const a)
{
    cout<<*a<<" ";
    *a = 9;
}
 
int main(void)
{
    int a = 8;
    Cpf(&a);
    cost <

C: The parameter transfer of custom types requires temporary objects to copy parameters. For the construction of temporary objects, the constructor needs to be called, which is a waste of time. Therefore, we adopt the method of const plus reference transfer.

And for the general int, double and other built-in types, we do not use the transfer method by reference.

Instance

#include
 
using namespace std;
 
class Test
{
public:
    Test(){}
    Test(int _m):_cm(_m){}
    int get_cm()const
    {
       return _cm;
    }
 
private:
    int _cm;
};
 
 
 
void Cmf(const Test& _tt)
{
    cout<<_tt.get_cm();
}
 
int main(void)
{
    Test t(8);
    Cmf(t);
    system("pause");
    return 0;
}

The result is 8.

For the return value of const modified function.

Const modifies the return value in three cases.

A: const modifies the return value of the built-in type, and modification has the same effect as unmodified return value.

Instance

#include
 
using namespace std;
 
const int Cmf()
{
    return 1;
}
 
int Cpf()
{
    return 0;
}
 
int main(void)
{
    int _m = Cmf();
    int _n = Cpf();
 
    cout<<_m<<" "<<_n;
    system("pause");
    return 0;
}

B: const modifies the custom type as the return value. At this time, the returned value cannot be used as an lvalue, nor can it be assigned or modified.

C: const modifies the returned pointer or reference. Whether to return a pointer to const depends on what we want the user to do.

Four, const modified class member function

The purpose of const modified class member functions is to prevent member functions from modifying the value of the called object. If we do not want to modify the value of a calling object, all member functions should be declared as const member functions.

Note: The const keyword cannot be used with the static keyword at the same time, because the static keyword modifies the static member function. The static member function does not contain the this pointer, that is, it cannot be instantiated. The const member function must be specific to an instance.

The following get_cm()const; function uses const member functions:

Instance

#include
 
using namespace std;
 
class Test
{
public:
    Test(){}
    Test(int _m):_cm(_m){}
    int get_cm()const
    {
       return _cm;
    }
 
private:
    int _cm;
};
 
 
 
void Cmf(const Test& _tt)
{
    cout<<_tt.get_cm();
}
 
int main(void)
{
    Test t(8);
    Cmf(t);
    system("pause");
    return 0;
}

If get_cm() removes the const modification, even if the const _tt passed by Cmf does not change the value of the object, the compiler thinks that the function will change the value of the object, so we try to make all functions that do not need to change the content of the object as const as required Member function.

What if a member function wants to modify a member of the object? At this time, we can use the mutable keyword to modify this member. The meaning of mutable is also changeable and easy to change. The members modified by the mutable keyword can be constantly changing, as shown in the following example.

Instance

#include
using namespace std;
class Test
{
public:
    Test(int _m,int _t):_cm(_m),_ct(_t){}
    void Kf()const
    {
        ++_cm; // error
        ++_ct; // correct
    }
private:
    int _cm;
    mutable int _ct;
};
 
int main(void)
{
    Test t(8,7);
    return 0;
}

Here we use ++_ct; to modify the value of _ct in Kf()const, but modify _cm via ++_cm will report an error. Because ++_cm is not modified with mutable.

This article address: https://www.linuxprobe.com/c-const-summary.html

Guess you like

Origin blog.csdn.net/u014389734/article/details/108314745