A comprehensive summary of C + + const __c++

Source: Internet
Author: User
Tags modifier volatile

C + + In the use of the Const keyword is very flexible, and using the const will greatly improve the robustness of the program, I based on all aspects of the information to summarize the following, I hope to help friends.

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

The role of a const

As shown in the following table:

No.

Role

Description

Reference Code

1

You can define a const constant

 

const int MAX = 100;

2

Easy to type check

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

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

3

To protect the things that are modified.

Prevents accidental modification and enhances the robustness of the program.

void f (const int i) {i=10;//error!}
If I was modified in the body of the function, the compiler would make an error.

4

can easily adjust and modify the parameters

Like the definition of a macro, you can do the same, you have changed

 

5

Provides a reference for a function overload

 

Class A
{
......
void f (int i) {...}//a function
void f (int i) const {...}//overload of previous function
......
};

6

Can save space and avoid unnecessary memory allocations

The const definition constant from the assembly point of view, just gives the corresponding memory address, rather than #define as given is the immediate number, so the const defined constants in the process of running the program only one copy, while the #define defined constants in memory have several copies

#define PI 3.14159//Chang
Const DOULBE pi=3.14159; Pi is not placed in ROM at this time
......
Double I=pi; The pi allocates memory at this time and is no longer assigned.
Double I=pi; Macro substitution during compilation, allocating memory
Double J=pi; No memory allocation
Double J=pi; Then make a macro substitution and allocate memory again.

7

Increased efficiency

Instead of allocating storage space for ordinary const constants, the compiler saves them in a symbol table, which makes it a constant during compilation, with no operation to store and read memory, making it highly efficient

 

ii. use of const

1. Defining constants
(1) The const modifier variable, the following two kinds of definition form are essentially the same. It means that the variable value of the type with the Const modifier is immutable.

TYPE const VALUENAME = value;
Const TYPE VALUENAME = value;


(2) Change the const to an external connection for expansion to global, the memory is allocated at compile time, and can be uninitialized, just as a declaration, which the compiler considers to be defined elsewhere in the program.

Extend const int valuename = value;

2, the use of const pointer
(1) The pointer itself is a constant variable
(char*) const pcontent;
Const (char*) pcontent;

(2) What the pointer points to is a constant variable
Const (char) *pcontent;
(char) const *pcontent;

(3) Both are not variable
const char* Const pcontent;

(4) There are also different ways to draw a line along the * number:
If the const is on the left side of the *, the const is used to modify the variable that the pointer points to, that is, the pointer to a constant;
If the const is on the right side of the *, the const is the cosmetic pointer itself, that is, the pointer itself is a constant.

3. Use const in function

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

void function (const int Var);

B. The parameter pointer refers to a constant variable

void function (const char* Var);

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

void function (char* const VAR);

D. parameter as reference, in order to increase efficiency and prevent modification. When a reference parameter is decorated:

void function (const class& VAR);//reference parameter cannot be changed within a function

void function (const type& Var); Reference parameters are invariant to constants within a function

Such a const reference pass is exactly the same as the most common function passed by value, and he prohibits all modifications to the referenced object, except that passing by value will first create a copy of the class object and then pass the past, and it passes the address directly, So this transfer is more efficient than passing by value. In addition, only a reference const pass can pass a temporary object, because the temporary object is a const attribute and is not visible, he has a short time in a local domain, so cannot use the pointer, only the reference of the Const pass can catch this guy.


(2) const modifier function return value
The const modifier function returns a value that is not very useful, and its meaning is essentially the same as the const-modified ordinary 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 ()//call when const int *pvalue = FUN2 ();
We can think of fun2 () as a variable, that is, the contents of the pointer are immutable.
c.int* Const FUN3 ()//Call time int * Const PVALUE = fun2 ();
We can think of fun2 () as a variable, that is, the pointer itself is immutable.

In general, when a function returns a value of an object, it is used for overloading the operator if it is declared as Const. Generally, it is not recommended to use the Const modifier return value type of a function as an object or as a reference to an object. The reason is as follows: If the return value is a const (const a test = a instance) or a reference to an object is const (const a& test = A instance), the return value has a const attribute. The return instance can only access public (protected) data members and const member functions in Class A and does not allow assignment operations, which is rarely used in general.


4, class-related const

(1) const modifier member variable
The const modifier member function of a class, which represents a member constant, cannot be modified, and it can only be assigned 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 modified member function
Const modifies a member function of a class, the member function cannot modify any of the non-const member functions in the class. Generally written at the end of the function to decorate.
Class A
{
...
void function () const; A constant member function that does not change the member variables of an object.

Nor can you call any of the non-const member functions in the class.
}

For a Const class object/pointer/reference, only the const member function of the class can be invoked, so the most important function of the Const modifier is to restrict the use of the const object.

A. A const member function is not allowed to modify any of the data members of its object.

B. A const member function can access a const member of an object while other member functions are not available.

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

· The const-Decorated class object represents the object as a constant object in which no member can be modified. The same is true for object pointers and object references.

· The const-decorated object, any non-const member function of the object, cannot be invoked 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

methods for converting a const type to a non-const type

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

· The constant pointer is converted to a very measured 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 measured object.

Iv. some suggestions for using const

· Bold use of the const, which will bring you endless benefits, but only if you have to understand the cause;

· To avoid the most common assignment operation errors, such as the const variable assignment, the specific visible study questions;

· Use of const in parameters should use a reference or pointer, rather than a generic object instance, for the reason above;

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

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

· The return value type is generally not defined as a const reference to an object except for overloaded operators;

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

v. Additional IMPORTANT notes

· Constant restrictions within a class: When using the initialization syntax inside such a class, the constant must be a constant expression

The integer or enum type that is initialized, and must be static and const forms.

· How to initialize constants inside a class: One method is static and const and is initialized 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; There is another way to initialize externally,

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

The this pointer is a const class type; If in the volatile member function, the this pointer is a

Volatile of the class type.

· The pointer returned by new must be a const type.

Related Article

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.