Const action in C + +

Source: Internet
Author: User

1. Replace # define.  

When it comes to using const instead of # define, why do you do it, of course, Const is better than # define, and one obvious difference is that const has a data type that can perform type safety checks, while # define is simply a replacement and this function. So we'll try to use

Const double PI = 3.1415926;

To replace this statement:

#define PI 3.1415926;//is best defined with a const

and the definition of # define is replaced before it enters the compiler, so that when it comes to compiling errors for this constant, the report is not a pi but a 3.1415926 constant, which brings debugging trouble.

Another advantage of using cosnt instead of # define is to reduce unnecessary memory allocations, such as:

#define PI 3.1415926//Macro Constants

Const DOULBE pi=3.1415926; Pi is not placed in ROM at this time

......

Double I=pi; Allocate memory for PI at this time, no longer assigned!

Double I=pi; Macro substitution during compilation, allocating memory

Double J=pi; No memory Allocations

Double J=pi; Another macro replacement, another memory allocation!

A const-defined constant has only one copy of the program while it is running, and the constant defined by # define has several copies in memory and a memory allocation!

2. Make an object (variable), value, pointer, reference cannot be modified.

This is the most common of all, and it is used to define constants and make them immutable.

It is very well understood to be used to decorate objects (variables) and is also one of the most frequently used const functions. But for pointers, it might not be good to understand, specifically, you can see the following code:

const int p//equals constant P

int const P//Ibid

The const int *A//means A is a pointer to a constant integer (cannot be changed by *p to the value of the variable pointed to, but the pointer is changed, this is most common in the function parameters, when you only refer to the value of the pointer passed in to the point of time plus const modifier, modified in the program will not pass the compilation, can reduce the bug)

int * Const A//indicates a is a constant pointer to an integer number (can modify the value of the variable pointed to, but cannot change the pointer point)

int const * Const A//indicates a is a constant pointer to a constant number (i.e. it is not possible to modify the value of a variable by *p or to change the pointer's direction)

Summary: This can be remembered, the const in front of who, that is, the const modification who, who immutable. Who reads before, such as the 3rd, read as a constant pointer, 4th, read as a pointer constant

3. Enable static objects of a class to be initialized inside a class

When we want to define a constant inside the class, we can use the const to decorate it, otherwise, we can't initialize it, and look at the following code

Class Print

{

Private

cannot be written as static int count = 10;

static const int count = 10;

String Info[count];

};

const int Print::count;

Of course, the cosnt constant can also be initialized by initializing the member list of the class constructor:

Class A

{

Public

A (int i=0): count (i) {}

Private

const int count;

};


4. Improve program robustness by modifying function parameters and return values

modifying function parameters with Const is a common behavior, see the following code:

Const bigint operator+ (const bigint& BIGVAR1, const bigint& BIGVAR2)

{return bigvar1.value+bigvar2.value; }

Since both BIGVAR1 and Bigvar2 are class types, in order to improve the efficiency of the pass-through, the object reference is used, but there is a problem that we cannot prevent the bigvar1 and BIGVAR2 values from being modified inside the function, and the solution can only be const. This is one of the common "const reference passes" that we use in the transfer of function parameters to non-intrinsic data types, which allows for high efficiency while preventing objects from being modified inside the function.

Then look at the const in front of the object (bigint front) it does not allow the following code to exist: (a+b) = C//a,b,c are bigint types

The above code is obviously meaningless, and it assigns a value to the result of an operation, and we should add a const to prevent such a code from happening.

For a class member function, if the data member is not modified, we should have const to declare that if I write such a function accidentally modifies the class's data members or calls non-const member functions, the compiler will give the relevant hints. Take a look at the following code:

Class Myprint

{

Public

Myprint ():p rintcount (0) {};

void print ();

int GetCount () const;

Private

Myprint (const myprint&);

myprint& operator= (const myprint&);

int printcount;

};

The const version of the subscript overload is called in the const member function, and non-const versions are generally used to modify values, such as cin>>x[i];

void Myprint::p rint () {}

int Myprint::getcount () const

{

++printcount; Error, const member function cannot modify data member of Class

Print (); Error, const member function cannot call non-const member function

return printcount;

}

Modifying a member function with a const actually modifies the this pointer, sostatic member functions cannot be declared as const, the reason is simple: the static member function does not have the this pointer. Here toNote the const member function in the keyword const is placed on the last side of the member function。

Sometimes I do want to modify the class's internal data clerk in the const member function, what should be done, fortunately, the standard C + + provides the keyword mutable to achieve, as long as the class data members precede the keyword mutable:

Class Myprint
{

Public

......

int GetCount () const;

Private

......

mutable int printcount;

};

......

int Myprint::getcount () const

{

++printcount;//correct because PrintCount has the keyword mutable modifier

......

return printcount;

}

Of course, there are other ways (using const_cast or indirectly through pointers to modify or pass the this pointer of the member function) can also achieve the purpose of the modification, but it is best to use mutable.

5. Use const to modify the member function of the overloaded class.

Sometimes we want to provide a const overloaded version of a member function for a class to suit the needs of different situations, such as

Class Vector

{

Private

int rep[size];

Public

const int & operator[] (int index) const// const version subscript overload

{

return Rep[index];

}

int & operator[] (int index)//non-const version subscript overload

{

return Rep[index];

}

}


In fact, the role of Const should be more than the above mentioned, but it can be said that some of the commonly used functions are referred to. Where appropriate use of cosnt should be made as far as possible, so that the program becomes simple and clear.

Finally, you can see the meaning of all the const in this function:

Const char* Const FOO (char const * Const STR) const

The first const indicates that the return type is const, that is, the return value of this function cannot be used as an lvalue.

The second const represents the immutability of the pointer, but it can be omitted in this, because the return type is already const.

The third cosnt represents the constant nature of STR, and its contents cannot be changed, and can be written in front of the char in front of it.

The fourth cosnt represents the constant nature of the STR pointer, which means that the pointer cannot point to another address.

The fifth cosnt represents the constant nature of this function (provided the member function of the Class) and cannot modify the data member of the class in which it resides.

Const action 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.