Usage of const in C + +

Source: Internet
Author: User
Tags types of functions

Const is a C language keyword, augmented by C + +, becomes powerful and complex to use. Const is used to define a constant variable (read-only variable), and when Const is used in conjunction with pointers, references, functions, and so on, the situation becomes much more complex. The usage of const is summarized in five ways below.

1.const position

The const position is flexible, in general, in addition to modifying the member functions of a class, the const does not appear at the end of the first statement. Examples are as follows:

#include <iostream>using namespace STD;intMainintargcChar* argv[]) {intI=5;Const intv1=1;int ConstV2=2;Const int* P1;int Const* P2;//The following three statements report a compilation error, why?     //const * int p3;    //int* Const p3=&v1;    //int * Const P3;    int*Constp3=&i;Const int*Constp4=&v1;int Const*Constp5=&v2;Const int& R1=v1;int Const& R2=v2;//The following statement reported a compilation error, why?     //const & int R3;    //The following statement warns you and ignores the const    int&ConstR4=i;cout<<*p4<<endl;return 0;}

Read the above procedure and draw the following conclusions:
(1) The program output is 1, the above program demonstrates the relationship between the location of the const and its semantics, seemingly complex,
There are actual rules to follow.
(2) const and data types are combined to form so-called "constant types", which can be declared or defined using a constant type.
Constant variable. When const is used to modify a type, it can be placed either before the type or after the type, such as the const int i and int const I are legal and equivalent. When declaring or defining a variable with a constant type, the const appears only before the variable.
(3) There can be no other identifier between the const and the modified type.
(4) The int const p and int const p are different declaration statements, because the former const modifier is int, the latter is const-modified int*. The former indicates that the pointer p points to an integer constant variable (the contents of the cell referred to by the pointer are not allowed to be modified), and the pointer itself can point to another constant variable, that is, p is a pointer to a constant-a constant pointer. The latter indicates that the value of the pointer p itself cannot be modified, and once p points to an integer variable it cannot point to another variable, that is, p is a pointer constant.
(5) The reference itself can be understood as a pointer constant, and using const before referencing is meaningless. In the example above int & const R4=I, Medium const is superfluous. That is, there is no reference to a constant, only a constant reference. The reference object is a constant that is not allowed by referencing and modifying the value of the referenced object.
In many cases, to express the same semantics, you can place a const in a different location. However, in some cases, the const can only be placed in a specific location, the example of a const with a double pointer, the code is as follows:

int  Main (int  argc,char  * argv[]) {//const with double pointer  Span class= "Hljs-keyword" >int const  **p1; int  * const  * p2; int  i=5 ; int  j=6 ; const  int  * ptr1=&i; int  * const  ptr2=&j; p1=&ptr1; p2=&ptr2; cout  <<**p1<<  <<**p2< <endl; return  0 ;} 

Read the above code to draw the following conclusions:
(1) The operating result of the program is: 5 6
(2) Int const *P1 and int const * P2 affirm that the meaning of the double pointer P1 and P2 is completely different. P1 not
is a pointer constant, the type of the variable it points to is int const (a pointer to an integral constant). P2 is also not a pointer constant, and the variable type it points to is int const (integer pointer constant). If you assign values by P1=&PTR1 and P2=&PTR2, a compilation error is generated.

Const members of 2.const objects and objects

Const defines a basic type of variable that is not allowed to modify the value of the variable. The const-decorated class's objects are called constant objects, and the const-decorated class-member functions are called constant functions. Examine the following code:

#include <iostream>using namespace STD;classa{intNum Public: A () {num =5;};voidDisp ();voidDisp ()Const;void Set(intn) {num=n;};};voidA::d ISP () {cout<<"Another version of Disp ()"<<endl;}voidA::d ISP ()Const{cout<<num<<endl;}intMainintargcChar* argv[]) {A A1; A1.Set(3);    A1.disp (); AConstA2; A2.disp ();return 0;}

The results of the program execution are:
Another version of DISP ()
5
Read the above procedure and draw the following conclusions:
(1) When the declaration of the constant function is separated from the definition, the Const keyword is used on both sides, or a compilation error occurs.
(2) Only a non-static member function of a class can be declared as a constant function, because a static member function does not contain the this pointer, which belongs to a class-level function. Other types of functions (such as external functions, etc.) cannot be declared as constant functions.
(3) A class of two member functions, if the function of the return value type, function name, function parameter list is identical, one is an ordinary function, and one is a normal function, then they constitute an overloaded relationship. As in the example above, void disp () and void disp () are const. This is because the void disp () and void disp () const have different signatures. C + + also takes this pointer as part of the parameter evaluation, since the function above is defined as a member function of class A, then they will eventually be treated as void disp (A *) and void disp (const A *), thus constituting an overload.
(4) When a function is called by a non-read-only object (such as A1), the version of its non-const function is searched first, and if it is not found, then its const function version is called. Instead of a constant object (A2), you can call only the constant function defined in the class, or a compilation error occurs.
(5) When there is a const and non-const version of a member function, a normal object should call the const function by establishing a constant reference to the object or a constant pointer to the object. As in the above program, to call the constant function disp () with the object A1, you can use the following statement:
(const a&) A1). DISP ();
Or:
((const *) &A1)->disp ();
(6) A part of a data member can also be defined as a constant, known as a constant member of a class object, in a non-read-only object. A non-static constant member of a class object must be initialized in the constructor, and only with the help of the initialization list, because the initialization list is initialized, and the constructor is assigned by an assignment operator, not initialized.

Parameters and function return values for 3.const modifier functions

Const is often used in defining functions, which are used primarily to modify parameters and return values. The goal is to have the compiler do a read-only check of variables for programmers to make the program more robust. Examine the following code:

voidDISP1 (Const int&ri) {cout<<ri<<endl;}voidDISP2 (Const inti) {cout<<i<<endl;}Const intDISP3 (Const int& RI) {cout<<ri<<endl;returnRI;}int& DISP4 (int& RI) {cout<<ri<<endl;returnRI;}Const int& DISP5 (int& RI) {cout<<ri<<endl;returnRI;}intMainintargcChar* argv[]) {intn=5;    DISP1 (n);    DISP2 (n);    DISP3 (n); DISP4 (n) =6; DISP5 (n);//DISP5 (n) = 6; it's wrong.GetChar ();return 0;}

The result of the program operation is:
5
5
5
5
6
Read the above code to draw the following conclusions:
(1) The formal parameter declaration of a const-modified pass call is constant and has no practical value. The declaration of void disp2 (cons tint i) in the example above is meaningless because the change of the parameter I does not affect the value of the argument.
(2) When the return value of a function is a value type, the const modifier has no meaning because the return value is a non-left
Value, which itself cannot be changed, the const int disp3 (cons tint& ri) In the above example is superfluous for the return value.
(3) When a const-modified formal parameter of a value type does not constitute a function overload, such as void disp (const int i) and void disp (int i). However, when Const modifies formal parameters of a non-value type (reference, pointer), it forms a function overload, such as void disp (const int& i) and void disp (int& i).

4. Common Misconceptions About const

(1) Misunderstanding one: The variable value modified with const must not be changed. When a const-modified local variable is stored in a non-read-only memory, it can be indirectly modified by a pointer.
(2) misunderstanding two: often quoted or often pointers, can only point to constant variables, which is a great misunderstanding. A constant reference or constant pointer can only indicate that the referenced object cannot be modified by the reference (or the pointer), as to what nature of the referenced object cannot be determined by the constant reference (constant pointer).

5. Converting a const type to a non-const type

Use the cons_cast operator in C + + to remove a const or volatile attribute from a composite type. When it is unwise to use const_cast, it can only be said that there is a design flaw in the program. See the following example for the use of the method:

void  consttest () {int  i;    cout  << "Please input a integer:" ;    cin  >>i; const     int  a=i; int  & R=const_cast  < int  &> (a);    //if written int& r=a; a compile error  ++r occurs; cout  <<a<<endl;} int  Main (int  argc,    char  * argv[]) {consttest (); return  0 ;}  

Program input 5, output 6.
Read the above procedure and draw the following conclusions:
(1) The syntax form of the const_cast operator is const_cast< type_id> (expression).
(2) Const_cast can only remove the const or volatile properties of the target, and cannot perform different types of conversions. The following conversions are wrong:
Cons Tint a={1,2,3};
char* p=const_cast< char*> (A);//cannot be converted from const int[] to char*
(3) A variable is defined as a read-only variable (a constant variable), then it is always a constant variable. Cosnt_cast cancels the override permission on the indirect reference, and cannot change the const property of the variable itself.
(4) You can also convert a const type* type to a type* type or convert a const type& to a type& type by using a forced type conversion in the traditional C language. However, the use of const_cast will be better, because the const_cast conversion ability is weak, the purpose is clear, not error-prone, and C-style forced type conversion ability is too strong, the risk is greater, it is recommended not to adopt C-style coercion type conversion.

Reference documents

[1] Chen Gang. Advanced Step-by-step tutorials for C + + [M]. Wuhan: Wuhan University Press, 2008.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Usage of const in C + +

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.