Object-oriented is an important feature of C ++.
However, the optimizations added by C ++ on the basis of C are also very dazzling.
Const can directly replace # define in C.
The following points are very important, and the consequences are also very serious.
Const
1. the qualifier declares that the variable can only be read
Const int I = 5;
Int J = 0;
...
I = J; // invalid, causing compilation errors
J = I; // valid
2. Initialization is required.
Const int I = 5; // valid
Const Int J; // invalid, causing compilation errors
3. reference the const constant in another connection file
Extern const int I; // valid
Extern const Int J = 10; // The constant cannot be assigned again.
4. Easy type check
The const method enables the compiler to learn more about the processing content.
# Define I = 10
Const long & I = 10;/* dapingguo reminder: Due to compiler optimization
In const long I = 10; I is not allocated memory, but has been directly substituted into 10
In the future reference, there will be no errors in the future code.
As a result, I memory allocation is explicitly provided with & I. However, once you close
There are optimization measures, even if const long I = 10; will cause subsequent compilation errors. */
Char H = I; // No error
Char H = I; // compilation warning, which may result in incorrect value assignment due to number truncation.
5. Avoid unnecessary Memory Allocation
# Define string "abcdefghijklmn/N"
Const char string [] = "abcdefghijklm/N ";
...
Printf (string); // The first memory allocated to the string
Printf (string); // The memory is allocated once for the string and will not be allocated later
...
Printf (STRING); // The second memory is allocated for the STRING.
Printf (string );
...
Since the const definition constant only provides the corresponding memory address from the Assembly perspective,
Instead of giving an immediate number like # define, the constant defined by const is
The program runs only one copy, while # The constants defined by define are in the memory.
Several copies.
6. constants can be initialized through functions.
Int value ();
Const int I = value ();
Dapingguo said: it is assumed that the target Code cannot be rewritten during ROM programming,
This statement will be invalid, but it can be changed as follows:
Const int & I = value ();
As long as the I address is out of ROM, it can be implemented: I is initialized through the function, and its
The value is not modified.
7. Is it true that the constant value of const cannot be modified?
Observe the following code:
Const int I = 0;
Int * p = (int *) & I;
P = 100;
By force type conversion, the address is assigned to the variable and the constant value of const can be changed.
8. distinguish between numeric constants and pointer constants. The following statements are quite interesting:
Int ii = 0;
Const int I = 0; // I is a constant and the I value will not be modified
Const int * p1i = & I; // The content indicated by the p1i pointer is a constant and may not be initialized.
Int * const p2i = & ii; // the pointer p2i is a constant and can be modified.
Const int * const p3i = & I; // the pointer p3i is a constant and the content referred to is also a constant
P1i = & ii; // valid
* P2i = 100; // valid
The usage of the const keyword in C ++ is very flexible, and the use of const will greatly improve the robustness of the program. For more information, see the const usage of Kang jiandong brother, I have supplemented and written this article.
1. Const constants, such as const int max = 100;
Advantage: const constants have data types, while macro constants do not. The compiler can perform type security checks on the former, while the latter only performs character replacement without type security checks. In addition, unexpected errors (marginal effect) may occur during character replacement)
2. Data Member of the const modifier class. For example:
Class
{
Const int size;
...
}
Const data members are constants only within the lifetime of an object, but they are variable for the entire class. Because the class can create multiple objects, the values of the const data members of different objects can be different. Therefore, the const data member cannot be initialized in the class declaration, because the compiler does not know the value of the const data member when the class object is not created. For example
Class
{
Const int size = 100; // Error
Int array [size]; // error, unknown size
}
Const data member initialization can only be performed in the class constructor initialization table. To create a constant in the entire class, use the enumerated constant in the class. For example
Class
{...
Enum {size1 = 100, size2 = 200 };
Int array1 [size1];
Int array2 [size2];
}
Enumerated constants do not occupy the storage space of objects. They are fully evaluated during compilation. However, the implicit data type of an enumerated constant is an integer, and its maximum value is limited. It cannot represent a floating point.
3. For details about how to modify the pointer in const, see the following formula:
Int B = 500;
Const int * a = & [1]
Int const * a = & [2]
Int * const a = & [3]
Const int * const a = & [4]
If you can differentiate the above four situations, congratulations! you have taken a great step. I don't know. It doesn't matter. We can refer to the practice on Item21 in Objective c ++. If const is on the left side of the asterisk, const is used to modify the variable pointed to by the pointer, that is, the pointer points to a constant. If the const is on the right side of the asterisk, the const modifies the pointer itself, that is, the pointer itself is a constant. Therefore, [1] is the same as [2], and the content pointed to by the pointer is a constant (The position of the const in the variable declaration is irrelevant ), in this case, the content cannot be changed, for example, * a = 3; [3] indicates that the pointer itself is a constant, and the content pointed to by the pointer is not a constant, in this case, the pointer itself cannot be changed. For example, a ++ is incorrect. [4] indicates that the pointer itself and the content pointed to are constants.
4. Const Initialization
Let's take a look at the initialization of the const variable.
1) Non-pointer const constant initialization: a B;
Const A = B;
2) const constant initialization:
A * D = new ();
Const A * c = D;
Or: const A * c = new ();
3) const constant initialization:
A f;
Const A & E = f; // in this case, e can only access the function declared as const, but cannot access
General member functions;
[Thinking 1]: Is the following assignment method correct?
Const A * c = new ();
A * E = C;
[Think 2]: Is the following assignment method correct?
A * const c = new ();
A * B = C;
5. In addition, some powerful functions of const are its application in function declaration. In a function declaration, const can modify the return value of a function or a parameter. For a member function, it can also be modified as a whole function. The usage of A & operator = (const A & );
Void fun0 (const A * );
Void fun1 () const; // fun1 () is a class member function.
Const A fun2 ();
1) modify the const of the parameter, such as void fun0 (const A * a); void fun1 (const A & );
When you call A function, use the corresponding variable to initialize the const constant. In the function body, perform the constant operation according to the Section modified by the const. For example, if the parameter is const a *, the content of the passed pointer cannot be changed to protect the content pointed to by the original pointer. If the parameter is const A & a, the passed referenced object cannot be changed, protects the attributes of the original object.
[Note]: The const parameter is usually used when the parameter is a pointer or reference, and can only modify the input parameter. If the input parameter uses the "value transfer" method, because the function will automatically generate a temporary variable for copying this parameter, this parameter does not need to be protected, so it does not need to be modified by the const.
[Conclusion] for non-Internal data type input parameters, the "value transfer" method should be changed to "const reference transfer" to improve efficiency. For example, change void Func (A a) to void Func (const A &)
For internal data type input parameters, do not change the "value transfer" method to "const reference transfer ". Otherwise, the function can not improve the efficiency, but also reduce the comprehensibility of the function. For example, void Func (int x) should not be changed to void Func (const int & x)
2) modify the const of the returned value, such as const A fun2 (); const A * fun3 ();
After the return value is declared, const is modified according to the "Modification Principle" to provide corresponding protection. Const Rational operator * (const Rational & lhs, const Rational & rhs)
{
Return Rational (lhs. numerator () * rhs. numerator (),
Lhs. denominator () * rhs. denominator ());
}
The return value can be modified with const to prevent such operations from being allowed: Rational a, B;
Radional c;
(A * B) = c;
The const is usually used to modify the return value to the object itself (non-referenced and pointer). It is often used when the binary operator reloads a function and generates a new object.
[Summary]
1. Generally, when the return value of a function is an object, if it is declared as a const, it is mostly used for the overloading of operators. In general, it is not recommended to use const to modify the type of the function's return value to an object or to reference an object. The reason is as follows: if the returned value is that an object is const (const A test = A instance) or an object is referenced as const (const A & test = A instance ), if the returned value has the const attribute, only the public (protected) data member and the const member function in Class A can be returned, and the value assignment operation is not allowed, this is rarely used in general.
2. if you add const to the return value of a function that uses the "pointer transmission" method, the content of the function return value (that is, the pointer) cannot be modified, the returned value can only be assigned to the same type pointer with const modifier. For example:
Const char * getstring (void );
The following statement causes a compilation error:
Char * STR = getstring ();
The correct usage is:
Const char * STR = getstring ();
3. There are not many cases where the function return values adopt "reference transfer". This method is generally only used in the class's callback value function to achieve chained expression. For example:
Class
{...
A & operate = (const A & other); // negative value function
}
A A, B, C; // A, B, C is the object of
...
A = B = C; // normal
(A = B) = C; // abnormal, but valid
If the return value of the negative value function is modified with const, the content of the returned value cannot be modified. In the previous example, a = B = C is still correct. (A = B) = C is incorrect.
[Think 3]: Can I define a value assignment operator to overload a function?
Const A & operator = (const A & );
6. Use of const in class member functions
Generally placed behind the function body, such as void fun () const;
Any function that does not modify data members is declared as const type. If the const member function is accidentally modified or other non-const member functions are called, the compiler reports an error, which greatly improves the robustness of the program. For example:
Class Stack
{
Public:
Void Push (int elem );
Int Pop (void );
Int GetCount (void) const; // const member function
Private:
Int m_num;
Int m_data [100];
};
Int Stack: GetCount (void) const
{
+ + M_num; // compilation error. An attempt is made to modify the data member m_num.
Pop (); // compilation error in an attempt to call a non-const Function
Return m_num;
}
7. const suggestions
1. Be bold in using const, which will bring you endless benefits, but the premise is that you must understand the original principles;
2. Avoid the most common assignment errors. For example, assign values to the const variable;
3. When using const in parameters, you should use references or pointers instead of common object instances, for the same reason as above;
4. const should be well used in three member functions (parameters, return values, and functions;
5. Do not set the function return value type to const easily;
6 except for the overload operator, do not set the return value type as a const reference to an object;
[Questions and Answers]
1. This method is incorrect because the declared pointer aims to change the content it points to, and the declared pointer e points to a constant, so it is incorrect;
2. This method is correct because the content pointed to by the Declaration pointer is variable;
3. This is incorrect;
In const A: operator = (const A & a), the const In the parameter list is correctly used. When such A value is assigned consecutively, the problem occurs:
A a, B, c:
(A = B) = c;
Because the return value of a. operator = (B) is a const reference to a, c cannot be assigned to a const constant.