Originally from www.codeproject.com
Author: Rahul Singh
The translator statement: Some places are unlocked by the original text, and the translator makes appropriate modifications according to their own understanding. If you have anything, please let's inform Coolgrass@sina.com or refer to the original text.
Introduction
When I write a program you need to use Const, or when I read someone else, I often stop thinking about it. Many programmers never need const, the reason is that even if they are useless, they are also coming. This article only discusses only the usage of Const, hoping to help improve the source code quality of the software.
Constant variable
The variable is modified with const, its value is not changed. Any code that changes this variable will generate compilation errors. Const is added before and after the data type.
E.g:
Void main (void)
{
Const Int i = 10; // i, j is used as a constant variable
INT const j = 20;
i = 15; // error, constant variable can not change
J = 25; / / error, constant variable can not change
}
Normally pointer
There are two ways when consisted with the pointer.
Const can be used to limit the pointer. That is to say, the memory address indicated by the pointer is not variable, but the contents of the memory pointing to the address can be arbitrarily changed. INT main (void) {INT i = 10; int * const j = & i; // often pointed to int in type variable (* j) ; / / can change the contents of the variables J ; // error, can not change often Memory address pointing by pointer}
Const can also be used to limit the memory pointer points to the pointer, but the memory address pointed to by the pointer can be changed. INT main (void) {INT i = 20; const INT * J = & I; / / pointer, pointing to int CONST * J = & I; J ; // The memory address pointed to by the INT; // * j) ; // error, can not change the memory content} Is it confused? Tell you that in the first example, const is used to modify the pointer J, J is not variable (the normal pointer pointing to the int variable); the second example, constraints are used to modify * J, * j is not variable (I.e., pointing to the INT constant).
These two ways can be combined to make pointers and memory contents. INT main (void) {INT i = 10; const INT * const j = & i; // points to the normal pointer J ; / / error of INT constant, can not change the address (* j) ; // error, Can't change the value of constant}
Const and reference references are actually the alias of the variable, there are several rules: Declaring variables must be initialized, and the reference cannot be pointed to other variables. Any changes to reference will change the original variable. The references and variables itself points to the same memory address.
The following example demonstrates the above rules: void main (void) {INT i = 10; // i and j are int = 20; int & R = I; // r is the reference INT & S of the variable I; / / Error, the declaration must initialize I = 15; // i and r are equal to 15 i ; // i and r are equal to 16 r = 18; // i and r are equal to 18 PrINTF ("Address of i = % u, address of r =% u ", & I, & r); // memory address is the same R = J; // i and r are equal to 20, but R is not reference R ; // i and r are equal to 21 , J is still equal to 20} with const modification reference to make the application not modified, but this does not delay the reference to reflect any changes to variables. Const is added before and after the data type. For example: void main (void) {INT i = 10; int J = 100; const INT & R = i; int const & s = j; r = 20; // is wrong, can not change content s = 50; // wrong, no Change content i = 15; // i and r are equal to 15 j = 25; // j and s are equal to 25}
When the const and member function declares the member function, constraints are added at the end, indicating that any data of the object cannot be changed within the member function. This mode is often used to represent the access mode of the object data read-only. For example: class myclass {char * str = "hello, world"; myclass () {// void constructor} ~ myclass () {// destructor}
Char Valueat (INT POS) const // const method is an accessor method {if (pOS> = 12) return 0; * str = 'm'; / / error, do not modify the object Return Str [POS]; // Return The value at position POS}}
CONST and overload function can also use const, consider the following code: Class myclass {char * str = "hello, world"; myclass () {// void constructor} ~ myclass () {// destructor}
Char Valueat (int POS) const // const same for is an accessor method {if (pOS> = 12) Return 0; return str [POS]; // Return the value at position POS} char & valueat (int POS) // passed Returns Set the memory content {IF (POS> = 12) Return Null; Return Str [POS];}} In the above example, Valueat is overloaded. Const is actually part of the function parameters, which limits this function in the first member function that cannot change the data of the object, and the second is not. This example is only used to illustrate that Const can be used to overload functions, and there is no practical meaning.
In fact, we need a new version of GetValue. If getValue is used on the right side of Operator =, it will act as a variable; if getValue is used as a one-dollar operator, the return reference can be modified. This use is often used to overload operators. The String class Operator [] is a good example. (This section is very bad translation, reads as follows: In reality due to the beauty of references just the second definition of GetValue is actually required If the GetValue method is used on the the right side of an = operator then it will act as an. accessor, while if it is used as an l-value (left hand side value) then the returned reference will be modified and the method will be used as setter. This is frequently done when overloading operators. The [] operator in String classes is a good escole.)
Class myclass {char * str = "hello, world"; myclass () {// void constructor} ~ myclass () {// destructor}
Char & Operator [] // can be used to change memory content {IF (POS> = 12) Return null; return str [pOS];}}
Void main (void) {myclass m; char CH = m [0]; // CH is equal to 'h' m [0] = 'm'; //m member STR becomes: Mello, World}
Const worry C / C , the manner that the data passes to the function is default that the value passes, that is, the copy of the parameter is generated when the parameter is passed to the function, so that any changes to this parameter are not changed. Extended to this function. Each time you call this function, you will generate a copy, the efficiency is not high, especially the number of functions calls. For example: class myclass {public: int x; char valueat (int POS) const // const method is an accessor method {if (pOS> = 12) Return 0; Return Str [POS]; // Return The value at position POS } Myclass () {// void constructor} ~ myclass () {// destructor} myfunc (int y) // value passes {y = 20; x = Y; // x and y are equal to 20.}}
Void main (void) {myclass m; int z = 10; m.myfunc (z); printf ("z =% d, myclass.x =% D", z, mx); // z unchanged, x is equal to 20.}
As can be seen from the example above, Z did not change because myfunc () is operated by Z's copy. In order to improve efficiency, we can use the reference delivery when passing the parameters. This is transmitted to the function is a reference to this parameter, and no longer a copy of the parameter. However, the problem is that if the parameters are changed inside the function, this change will extends to the outside of the function, and it is possible to cause errors. Plus Const modification before the parameter guarantees that the parameter will not be changed inside the function. Class myclass {public: int x; myclass () {// void constructor} ~ myclass () {// destructor} int myfunc (const INT & Y) // Reference, no copy {y = 20; // error, Cannot modify constant variable x = y}}
Void main (void) {myclass m; int z = 10; m.myfunc (z); printf ("z =% d, myclass.x =% D", z, mx); // z unchanged, x is equal to 10.}
In this way, Const makes you can't write this kind of simple security mechanism, maybe when it will fall, you will take your code. You should use the const reference as much as possible, by declaring your function parameters as a constant variable (any possible place) or define the const method, you can effectively establish such a concept: This member function does not change any function Parameters, or the data of any object is not changed. Other programmers will not worry about their data to be changed when using the member functions you provide.