This article records the contents of the Const keyword in C + +, divided into 3 parts, the difference between const and define, the role of Const, the use of Const.
The difference between const and define
The role of the const
- Const is used to define constants: The compiler can perform security checks on static data types.
- const modifier function Formal parameter: When the parameter is a custom type or abstract data type, you should change "value passing" to "Const & Pass" to improve efficiency as follows:
void Fun (a a); inefficient, the function body produces a type of temporary object for copying parameter A, the construction, copying, and destruction process of the temporary object will consume time.
void Fun (A const &a), highly efficient. Reference does not produce a temporary object, saving time, but the light reference may change the value of a, so add a const
- The return value of the const modifier function: For example, if the return value of a function that is passed by pointer is const, the return value cannot be directly modified, and the return value can only be assigned to a const-decorated pointer of the same type. As follows:
const char *getchar () {}
Char *ch = GetChar ();//error
const char *ch = GetChar ();//correct
- Const-Decorated class member function (function definition body): Any function that does not modify the data member should be decorated with a const so that the compiler will error when the data member is accidentally modified or a non-const member function is called. int GetChar (void) const;
Instance code:
Summary: In the Declaration and definition of a class member function, a const function cannot modify its data member. Const object, cannot reference a non-const member function.
Use of const
C + + Const && define