A comprehensive summary of C + + const

Source: Internet
Author: User

turn from: http://blog.csdn.net/Eric_Jo/article/details/4138548; in C + + The use of the Const keyword is very flexible, and using the const will greatly improve the robustness of the program, I based on the information found in various aspects 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

Provides a reference for function overloading

 

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

6

const definition constants from the assembly point of view, only the corresponding memory address is given, rather than the number of immediate numbers, as defined by # define, so the const definition of the constant in the program runs only one copy, and # Define defined constants have several copies in memory

#define PI 3.14159  //Macro Constants const Doulbe Pi=3.14159 ;  //at this time did not put Pi into ROM ... double i=pi;  //this time to allocate memory for PI, no longer assigned! Double I=pi;  //the macro substitution during compilation, allocating memory double j=pi;  //no memory allocation double J=PI;  //another macro replacement, once again allocating memory!

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 a constant immutable (char*) const pcontent; Const (char*) pcontent;
(2) The content pointed by the pointer is a constant immutable const (char) *pcontent; (char) const *pcontent;
(3) Both are immutable const char* const pcontent;
(4) There are different ways to line up along the * number: If the const is on the left side of *, then the const is used to decorate the variable pointed to by the pointer, that is, the pointer to a constant, if the const is on the right side of *, Const is to decorate the pointer itself, that the pointer itself is a constant.

3 , use in functions CONST

(1) const modifier function parameter A. Arguments passed in can not 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); the//reference parameter cannot be changed within the function

void function (const type& Var); the//reference parameter is constant within the function

Such a const reference pass is exactly the same as the most common function by value, and he forbids all modifications to the referenced object, except that passing by value creates a copy of the class object first,   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 property, and   and is not visible, he has a short time in a local domain, so you cannot use pointers, only the const pass of the reference can catch this guy.

(2) Const  modifier function return value const-modifier function return value It's not a lot of practical, Its meaning is basically the same as the Const modifier for ordinary variables and pointers. A.const int fun1 ()  //this is actually meaningless, because the parameter return itself is an assignment. B. const int * fun2 ()  //called when Span class= "apple-converted-space" > 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 ()  //called  int * Const PVALUE = fun2 ();  //We can think of fun2 () as a variable, that is, the pointer itself is immutable.

In general, when the return value of a function is an object, if it is declared as const, it is used for overloading the operator. In general, it is not recommended to use the const-modifier function's return value type as an object or as a reference to an object. The reason for this is that if the return value is const for an object (const A test = a instance) or a reference to an object is const (const a& test = A instance), the return value has a const property, The return instance can only access the public (protected) data members and the const member functions in Class A, and it is not allowed to be assigned operations, which is rarely used in general cases.

4 , class-related CONST

(1) The const modifier member Variable const modifies the member function of a class, 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) {}; //Can only be assigned in the initialization list}

(2) The 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; //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.  Example: Class AAA { void func1 (); void Func2 () const;  } const AAA aobj; Aobj.func1 (); Xaobj.func2 (); correct
Const aaa* aobj = new AAA (); aobj-> func1 (); xaobj-> Func2 (); correct

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

Use const_cast for conversion. usage: const_cast <type_id> (expression) This 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.

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.