"C + + Const Detailed Summary"-reproduced

Source: Internet
Author: User
Tags modifier volatile

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.

I. The role of const

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

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;  //does not put Pi in ROM at this time
                The
double i=pi;   //allocates memory for Pi 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;  // 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, the use of const

1. Define 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. Use the const pointer
(1) The pointer itself is constant immutable
char* const pcontent;

(2) The content pointed to by the pointer is a constant variable
const char *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 const in function

(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 and the most common function by the value of the effect is exactly the same, he forbade all changes to the referenced object, the only difference is that by value passing will first establish 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 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 pointers, only the const pass of the reference can catch this guy.


(2) const modifier function return value
The const modifier function returns a value that is not practical, and its meaning is basically the same as the const-modified ordinary variable and the pointer.
a.const int fun1 ()This is actually meaningless, because the parameter return itself is the 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 ()Called when 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 reasons are as follows:

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) A const-decorated member variable
A member function of a const-decorated class that represents a member constant that cannot be modified, and that it can only be assigned to a value in the initialization list.
    class A
    { 
Span style= "font-family:"comic sans ms", sans-serif ">         ....
         const int nvalue;         //member constants cannot be modified
         ....
         a (int x): Nvalue (x) {};  //can only be assigned a value 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 (); correct

    const aaa* aobj = new AAA ();
    aobj-> func1 (); x
    aobj-> Func2 (); correct

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

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. some suggestions for using the const

    • 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 inside this class, the constant must be an integer or enum type initialized by a constant expression, and must be in the form of static and Const.
    • 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 approach 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;
    • If 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 class type.
    • The pointer returned by new must be of type Const.

"C + + Const Detailed Summary"-reproduced

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.