Turn: A comprehensive summary of C + + const

Source: Internet
Author: User
Tags volatile

Turn: A comprehensive summary of C + + const

The use of the Const keyword in C + + is very flexible, and using the const will greatly improve the robustness of the program, I found in various aspects of the information summarized below, hoping to help friends.

Const is a type modifier commonly used in C + +, which refers to a type that uses the type modifier const description, and the value of a constant type variable or object cannot be updated.

First, Const function

This is shown in the following table:

No.

Role

Description

Reference Code

1

You can define Const constants

 

const int MAX = 100;

2

Easy to type check

Const constants have data types, and macro constants do not have data types. The compiler can perform type safety checks on the former, but only character substitution for the latter, no type security checks, and unexpected errors in character substitution

void f (const int i) {...}
Type check for incoming parameters, do not match to prompt

3

Can protect something that's been modified.

Prevent accidental modification and enhance the robustness of the program.

void f (const int i) {i=10;//error!}
If I is modified in the function body, the compiler will error

4

It is easy to adjust and modify parameters.

As with the definition of a macro, you can do the same, change

 

5

class A
{
            ...
 void F (int i)        {...}  //a function
 void f (int i) const {...}  //overloads of the previous function
           ...
};

6

Saves space and avoids unnecessary memory allocations

Const definition constants from a compilation point of view, just give the corresponding memory address, instead of the immediate number as given in # define, so the const definition of the constant in the program run only one copy, and # define the constants in memory have several copies

#define PI 3.14159//Macro Constants
Const DOULBE pi=3.14159; 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!

7

Increased efficiency

The compiler typically does not allocate storage space for ordinary const constants, but instead saves them in the symbol table, which makes it a constant during compilation, without the storage and read memory operations, making it highly efficient

 

Second, Const the Use

1 , Defining Constants
(1) The const modifier variable, the following two definitions form is essentially the same. The meaning of this is that the const-modified variant of type ' value ' is immutable.

TYPE const VALUENAME = value;
Const TYPE ValueName = value;
(2) Change the const to an external connection, which is used to enlarge to the global, the memory is allocated at compile time, and can be uninitialized, just as a declaration, the compiler thinks it is defined elsewhere in the program.

Extend const int ValueName = value;

2 , means Needles Use CONST
(1) The pointer itself is constant immutable
(char*) const pcontent;
Const (char*) pcontent;
(2) The content pointed to by the pointer is a constant variable
Const (char) *pcontent;
(char) const *pcontent;
(3) Both are not variable
const char* Const pcontent;
(4) There are different ways to line up along the * number:
If the const is on the left side of the *, the const is used to modify the variable pointed to by the pointer, that is, the pointer is constant;
If the const is on the right side of *, const is the modifier pointer itself, that is, the pointer itself is a constant.

3 , use in functions CONST

(1) const modifier function parameters
A. The passed arguments cannot be changed within the function (meaningless because Var itself is a formal parameter)

void function (const int Var);

B. The contents of the parameter pointer are constant

void function (const char* Var);

C. The parameter pointer itself is constant immutable (also meaningless because char* var is also a formal parameter)

void function (char* const VAR);

D. Parameters are references, in order to increase efficiency and prevent modification. When modifying reference parameters:

void function (const class& Var); Reference parameters cannot be changed within a function

void function (const type& Var); The reference parameter is constant within the function is not variable

Such a const reference pass is identical to the most common function by value, and he prohibits all modifications to the referenced object, except that passing by value first establishes a copy of the class object,  then passes the past, and it passes the address directly , so this delivery is more efficient than passing by value. In addition, only the Const pass of the reference can pass a temporary object, because the temporary object is a const attribute,  and is not visible, he has a local domain for a short time, so you cannot use a pointer. Only the const pass of the reference can catch this guy.
(2) const  modifier function return value
    const The value of the modifier function is not many, its meaning is basically the same as the Const modifier common variable and the meaning of the pointer.
    a.const int fun1 ()  //This is actually meaningless, because the parameter return itself is an assignment.
    b. const int * FUN2 ()  //called when  const int *pvalue = fun2 ();  
                           //We can think of fun2 () as a variable, that is, the pointer content is immutable.
    c.int* Const FUN3 ()   //Call  int * Const PVALUE = fun2 ();  
  & nbsp;                       //We can think of fun2 () as a variable, that is, the pointer itself is immutable.

4 , class-related CONST

(1) const modifier member variable
The Const modifier class's member function, which represents a member constant, cannot be modified, and it can only be assigned to a value in the initialization list.
Class A
{
...
const int Nvalue; Member constants cannot be modified
...
A (int x): Nvalue (x) {}; You can only assign values in the initialization list
}
(2) const modifier member function
Const modifies a member function of a class, the member function cannot modify any non-const member function in the class. Usually written at the end of the function to modify.
Class A
{
...
void function () const; The constant member function, which does not change the member variable of an object.

You cannot call any of the non-const member functions in the class.
}

For const class objects/pointers/references, only const member functions of the class can be called, so the most important role of the Const modifier member function is to restrict the use of Const objects.

A. The const member function is not allowed to modify any one of the data members of the object it resides on.

B. The const member function has access to the const member of the object, while the other member functions are not available.

(3) Const modifier class object/object pointer/object reference

· The const-Decorated class object indicates that the object is a constant object, and any of its members cannot be modified. The same is true for object pointers and object references.

· Const-Decorated object, any non-const member function of the object cannot be called because any non-const member function has an attempt to modify the member variable.
For example:
Class AAA
{
void Func1 ();
void Func2 () const;
}
Const AAA Aobj;
Aobj.func1 (); X
AOBJ.FUNC2 (); That's right

Const aaa* aobj = new AAA ();
Aobj-> func1 (); X
Aobj-> Func2 (); That's right

Third, the Const type conversion to non- Const Types of methods

Use const_cast for conversion.
Usage: const_cast <type_id> (expression)
The operator is used to modify the const or volatile properties of a type. In addition to const or volatile adornments, the type_id and expression types are the same.

· The constant pointer is converted into a very pointer, and still points to the original object;

· A constant reference is converted to a very literal reference and still points to the original object;

· A constant object is converted to a very mass object.

Iv. Use of Const Some of the recommendations

· The bold use of const will bring you endless benefits, but only if you have to figure it out;

· To avoid the most general assignment error, such as assigning a const variable to a value, the concrete visible study questions;

· Using const in parameters should use a reference or pointer instead of a generic object instance for the same reason;

· The three usages of const in member functions (parameters, return values, functions) should be used very well;

· Do not easily set the return value type of the function as const;

· In addition to overloading operators, it is generally not to make the return value type a const reference to an object;

· Any function that does not modify a data member should be declared as a const type.

V. Supplementary IMPORTANT Notes

· Constant restriction within a class: When using the initialization syntax of this class, the constant must be a constant expression

An integer or enum type that is initialized, and must be in static and const form.

· How to initialize constants inside a class: One method is to use static and const and initialize externally, for example:

Class A {public:a () {} private:static const int i; file://note must be static! };

const int a::i=3; Another very common method is to initialize the list: class A {public:a (int

i=0): Test (i) {} private:const int i; Another way is to initialize it externally,

· If in a non-const member function, the this pointer is just a class type, or if in the const member function,

The this pointer is a const class type, and if in a volatile member function, the this pointer is a

The volatile class type.

· The pointer returned by new must be of type Const.

Turn: A comprehensive summary of C + + const

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.