Const usage summary in C/C ++
I.const
Basic functions and usage
1. Declare the qualifier as read-only
The usage is as follows: add a keyword before/after the typeconst
, The variable must be initialized; otherwise, the compilation is incorrect; the variable cannot be assigned a value again; otherwise, the compilation is also incorrect.
Example:
Const int I = 50; // The const int j is correctly compiled; // The compilation error int k = 0; I = k; // The compilation error k = I; // The compilation is correct
2. It is used to modify function parameters to prevent them from being modified.
Usage 1: If the parameter isconst A* a
, You cannot change the pointer content passed by the function. This protects the content pointed to by the pointer,This modifier cannot change the content stored by the pointer pointing to the address, but the pointera
The specified address can be changed.For example:
Void Test (const int * a) {* a = 1; // error, * a cannot be assigned a = new int (10086); // correct, open up a new space for pointer a and Set * a = 2} int main () {int * a = new int (10000); Test (a); return 0 ;}
Usage 2: If the parameter isconst A& a
, Changes the referenced object passed in by the function to protect the attributes of the original object.
For custom data types, the reference transmission speed is faster. If you do not want to change the original value, you can useconst
To protect parameters, as shown in the following example:
Void Test (const int & a) // protection of a in L7 will not be changed {a = 2; // error, a cannot assign a value to a constant} int main () {int a = 3; Test (a); return 0 ;}
In fact, for the internal data type (for example, in the above exampleint
Type), passed by reference will not make the speed faster. If you use a reference parameter, it is generally used to change the parameter value. If you do not want to change the parameter value, you can directly pass the value without usingconst
. For custom data type input parameters, to improve the speed and efficiency, you should useconst
+ "Pass by reference" instead of "pass by value. For example:
Convert Functionsvoid Test(A a)
Change to->void Test(const A &a)
3. Used to modify the function return value
Usage 1: Useconst
Modifying the return value to the object itself (non-referenced and pointer) is often used when the binary operator reloads a function and generates a new object.
Example:
Const Rational operator * (const Rational & lhs, const Rational & rhs) {return Rational (lhs. numerator () * rhs. numerator (), lhs. denominator () * rhs. denominator ();} Rational a, B; Radional c; (a * B) = c; // Error
Usage 2: Not recommendedconst
When the type of the return value of a modifier is an object or an object is referenced. The reason is as follows: if the returned value isConst (const A test = A instance)
Or the reference of an object isConst (const A & test = A instance)
, The returned value hasconst
Attribute, only public (protected) data members andconst
Member functions, which are rarely used in general and are not allowed to be assigned values. An example is as follows:
Class A {public: int y; A (int y): x (x), y (y) {}; void Sety (int y) {this-> y = y ;}}; const A Test1 (A a) {return a;} const A & Test2 (A & a) {return ;} int main () {A a (2); Test1 (). sety (3); // error, because the returned value of Test1 (a) is a const and cannot be modified by Sety (3) Test2 (). sety (3); // error, because the returned value of Test1 (a) is a const, And the return 0 cannot be modified by Sety (3 ;}
Usage 3: Add a pointer to the return value of a function.const
The content of the function return value (that is, pointer) cannot be modified. The return value can only be assignedconst
The same type of pointer. Example:
Const char * GetString (void) {} int main () {char * str1 = GetString (); // error const char * str2 = GetString (); // return 0 correctly ;}
Usage 4: there are not many cases where the return value of a function uses "reference transfer". This method is generally only used in the class assignment function to implement chained expression. Example:
Class A {// the return value of the following value assignment function is modified with const. The content of the returned value cannot be modified with A & operate = (const A & other);} A a A, B, c; // a, B, and c are objects A = B = c; // correct (a = B) = c; // error, the return value of a = B cannot be assigned another value.
4. Add a keyword to the function body of the class member functionconst
Add a keyword after the function body of the class member functionconst
, Such:void fun() const;
Data members are not modified during the function process. If you are writingconst
When a member function is called, the data member is accidentally modified or other non-const
Member functions, the compiler will report errors, which greatly improves the robustness of the program.
If it is not a member function in the class, there is no effect,void fun() const;
Andvoid func();
Is the same.
5. Reference constants in another connection file
Method: Add a keyword before the typeextern const
, IndicatesReference constantTherefore, this constant cannot be assigned again. For example:
Extern const int I; // The correct extern const int j = 10; // The constant cannot be assigned again.
II.const
Constant and#define
Difference
1.const
Constants have data types, while macro constants do not.
Macro constants only replace simple characters without type security check, and unexpected errors may occur during character replacement, such:
# Define I = 10 const long & I = 10; // due to compiler optimization, so that when const long I = 10, I will not be allocated memory // But 10 has been directly substituted into future references, as a result, there will be no errors in future code // once you close all optimization measures, even if const long I = 10 will cause subsequent compilation errors. Char h = I; // correct char h = I; // compilation warning, which may cause incorrect value assignment due to number Truncation
2. Use const to avoid unnecessary Memory Allocation
From the Assembly perspective,const
Defining constants only gives the corresponding memory address, not#define
The same number is given immediately, so,const
The defined constant has only one copy during the program running, while#define
The defined constants have several copies in the memory. Example:
# Define k Hello world! Const char pk [] = Hello world !; Printf (k); // The first memory printf (pk) is allocated for k; // The memory is allocated for the primary key once, and no printf (k) is allocated in the future ); // The second memory printf (pk) is allocated to k );
Iii. Useconst
Some precautions
1. Modifyconst
Constant Value
In the following example,i
Isconst
Modified variables can be modifiedi
Perform type forced conversion, assign the address to a new variable, and then modify the new variable to change the originalconst
The constant value of the modifier.
const int i=0;int *p=(int*)&i;p=100;
2. the const cannot be declared as const.
3. const data member initialization can only be performed in the class constructor initialization table
Class A {public: const int a; A (int x): a (x) // correct {a = x; // error }};
4. Useconst
Reference or pointer should be used instead of general object instance
Rational Useconst
In the three usage methods of member functions (parameters, return values, and functions), generally, do not set the function return value typeconst
In addition, do not set the return value typeconst
Reference.
5.const
Modify the pointer
In the following cases,const
The effect is the same when it is placed at the front and back of the variable declaration character. In this case, the pointer is not allowed.a
To change the content:
int i;const int *a = &i;int const*a = &i;
However, Ifconst
In the left side of the asteriskconst
Is used to modify the variable pointed to by the pointer, that is,The Pointer Points to an address. The content of this address is unchangeable.Ifconst
On the Right of the asterisk,const
Is to modify the pointer itself, that isThe pointer itself is a constant.:
Int I; // the following line indicates that a is a pointer, you can point to any int constant or int variable // It always treats the target it points to as an int constant // You can also write it as int const * aconst int * a = & I; // The following line indicates that a is a pointer constant. // during initialization, it must point to an int variable. // then it cannot point to another place. int * const a = & I;
6. 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. In the following example, a ++ is incorrect:
Int * const a = & I; a ++; // error. The a pointer itself is a constant and cannot point to another place.
7. When the pointer itself and the content pointed to by the pointer are constants
In this case, it can be written as follows:
const int * const a = &i;
8. The reference returned by the const member function is also the const
# Include
Using namespace std; class A {public: int x; void set (int x) {this-> x = x;} // reference returned by the const member function is also const, a // if you remove the const in front of A &, an error will occur. // because the returned object is a const object, the returned content is not const // and the returned content is inconsistent with the returned type. const A & Test1 () const {// error. This is a feature of the const member function x = 2; // not limited to * this. No matter what the returned result is, even if it is an object defined as A non-const, return * this ;}; int main () {a, B; // correct, although a const is returned, another non-const is used to receive B =. test1 (); // error. Since it is an alias, the alias type must be the same as the original one. A & c =. test1 (); // correct although in. in Test1 (), a cannot be changed, but here the scope of this member function is displayed. set (2); // correct. B receives. content of the data returned by Test1 (), but it is not const B. set (2); // error. A. test1 () is an object. This object is its return value // although it has no name, it is. the return value of Test1 () // The value is. value returned by Test1 (). The type is. type returned by Test1 (). test1 (). set (2); return 0 ;}
9.mutable
Declare data as a variable data member
In C ++,mutable
Is to use a small number of keywords, its role is: if a function isconst
Modified, it will not be able to modify its member variables, but if a member variable ismutable
If it is modified, it can be modified.
mutable
It can be used to indicate that even if the member function or class variable isconst
A member can also be modified. Conversely, a variable data member can never becomeconst
, Even if it isconst
Object.
Class A {public: int x; mutable int y; A (int a, int B): x (a), y (B) {}}; int main () {const A a (0, 0); // The const object must initialize. x = 1; // error. y = 2; // correct. mutable modification allows the Member to be modified, even if object a is const return 0 ;}