C++ const qualifier

Recently, I reviewed const through online materials, and after comparing it with professional books, I found that there are many errors on the Internet, so I will make a note here.

1. const defines constants:

Once created its value cannot be changed, so it must be initialized.

If it is initialized with an expression, it will be initialized at runtime; if it is initialized with a value, it will be initialized at the compilation stage, and the compiler will replace all the places where the variable is used with the corresponding value. For this reason, the const object is set by default to only It is valid within the file, but const can be modified with the extern keyword to make it available in other files.

(例:const int x=5; const int y=init(); int *const z=&Z;)

2. Constant reference/pointer:

A reference/address to a constant/pointer cannot be used to modify the object it is bound/pointed to. (A lot of information on the Internet says that the pointed object cannot be changed. In fact, it cannot be changed through him. At the same time, the value of the pointer itself can also be changed. References (just aliases are not variables) cannot.)

However, only constant pointers can be used to store constant addresses, which may be the reason for errors in online materials.

(例:const int &x=y; const int *z=&Z;)

3. Use on the function:

When the function parameter is a constant pointer, it can avoid changing the content of the position pointed to by the parameter pointer inside the function.

When const is used to modify the function body, put it at the end of the line of the function body, indicating that in the function body, the data members of the object cannot be modified, and non-const member functions cannot be called.

(例:void fun1(const int x){};     void fun2()const;)

Guess you like

Origin blog.csdn.net/WindRushNight/article/details/122986771