Overview of C + + const

Source: Internet
Author: User

1,Cin LanguageConstwith theC + +in theConst

void Main () {  const int a = ten;  int *p = (int*) &a;  *p =;  printf ("%d", a);}

Compare the above code in C and C + + to Execute the result:C: print ;C + + : Print 0 .

Thus, the const in C is a "counterfeit",a const in C+ + is a true constant.

Reason: TheC language directly allocates memory for a.

C in the language Const variables are read-only variables and have their own storage space. the C + + compiler handles const by: When a constant declaration is encountered, in the "Symbol table" (C + + The compiler specifically sets) to put a constant in the use of a , directly in the symbol table to take the value. So the question is, how do we explain the address?

A. if the use of constants is found in the compilation process, the values in the symbol table are replaced directly;

B. If the use of extern(which needs to be used in other files) or the & operator is found in the compilation process , the the const constant is also allocated specifically for storage space.


as you can see, after taking the address of the const variable,A separate space is allocated for "a". There is no relationship to a in the symbol table .


2,Constwith the underlying data type:

   const int bufsize = 512. The value of the bufsize can no longer be changed. Any attempt to assign a value to a bufsize will raise an error.

The const object must be initialized since the const object cannot be changed once it has been created. int i=12;const int ci=i; You can also use another object (which is not const) to initialize the Const object:

。 Int j = ci. Once the copy is complete, the new object is not related to the original object. { int i =; const int J = i; Initialize int k = j; int m = +; j = m; Assignment, compilation Error}

by default, theconst object is only valid within the file. When a const object of the same name appears in multiple files , it is actually equivalent to defining separate variables in different files.

Assuming that the const object needs to be shared between different files, it is necessary to add the extern keyword to the const object, whether it is declared or defined .

Note can only be defined once:extern const int bufsize =. is generally included in the header file.

Declare directly when used:extern const int bufsize; no longer defined, otherwise an error occurs.

extern That 's the explanation. bufsize is not unique to this document, it is defined elsewhere.


3,ConstWith reference
void Main () {//Pair const object can only be referenced by constants int CI = 100;  Constant Object const int &ri = CI;          Correct: the reference and its corresponding object are constant//ri = 100;      Error:ri is a reference to a constant//int &r2 = CI;    Error: To point a very important reference to a constant object, assuming it is correct, then you will be able to change the value of CI by changing the R2, CI obviously can not change.   A constant reference agrees to be bound to a number of objects, literals, general expressions ———— Exceptions 1 int i = 50;        const int &CRI1 = i;      A very mass of object const int &CRI2 = 500;    literal value const int &CRI3 = i * 2;          General expression int r4 = CRi1 * 2; Correct: The constant feature of CRI1 only works when the changes are run, and the copy assignment does not change.   Once the copy is complete, the new object is not related to the original object.        int &R5 = CRI1 * 2; Error: Point A very important reference to a constant object. Assumptions are correct. Then you will be able to change the value of CRI1 by altering the R5, CRi1 obviously cannot change.

/* * * * * * * * * * * * generally. The referenced type must match the type of the object it refers to. * What exactly happens when a constant reference is bound to the second type? * Double d = 3.14; const int &ri = D; * CONST INT TMP = D; A transient integer constant const int &ri = d is generated by a double-precision floating-point number; Let ri bind this temporary constant * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * int &RJ = j; Reference RJ Binding Object J Const int &CJ = j; Constant reference CJ also binds object J. But do not agree with CJ to change the value of j RJ = 1000; Modified by RJ J,j is changed to//CJ = 1000; cout << "J:" << J << ", CJ:" << CJ << Endl; j:1000, cj:1000}


Const reference passing object (non-built-in type):

(1) High efficiency: No matter what new objects are created, they do not invoke constructors or destructors of any kind. (Built-in type values are passed in a high-efficiency manner)

(2) The object can be prevented from being split: Assume that a derived class object is assigned a value to the base class in a value-passing manner. The attributes of a derived class are divided by all, leaving only a base class object.


4,Constwith the pointer

A pointer or reference to a constant. Just pointers or references "self-righteous", they think themselves point to the constant, so consciously do not change the value of the object it points to. (However, a constant pointer or reference can be pointed to a quantity, and the amount can be changed in other ways.)

Pointers are objects, and references are not! So. The pointer itself is not a constant and the pointer refers to a constant that is not two independent of the problem!

Top-level const-The pointer itself is a constant!

Underlying const-The object that the pointer refers to is a constant.

void Main () {int i = ten, M = 20;     const int CI = +, CM = 200;        The first to second meaning, representing a constant shaping number, whatever attempts to assign a and B to the behavior will throw an error const int a = 0;              the int const B = 1 must be initialized;    The third c is a pointer to a constant number of shapes (the memory data pointed to cannot be altered, but can be changed by itself) const int *C1 = &ci;        int *C2 = &ci;          The address where the constant is stored, only the pointer to the constant can be used const int *C = &i;               *c = m;                 C refers to the memory data is const (C's self-perception), that is, cannot be "directly modified" by *c C = &m; The value of C is the consent change (the underlying const). Change the direction of C.     Let C point to a different memory space cout << *c << Endl;    20//Fourth D constant pointer ———— The pointer itself is a constant (pointer variable (pointing) cannot be changed, but it points to the memory space can be changed) int II = 0;    int * Const D =?               D will always point to II (top-level const), not agree to change the value of D *d = 250; The pointer itself is a constant and does not mean that it cannot be changed by changing the value pointed to by the pointer.

(depending on the object to which it is directed) cout << II << Endl; II was changed to 250. (d points to a volume)//fifth E a pointer to a constant shape (the pointer and the memory space it points to, can not be changed) const int PI = 123; const INT * Const E =π//e object value and e the address stored by itself cannot be changed}


5,Constwith member functions

The purpose of implementing a const with a member function is to confirm that the member function can be used on a const object (the non-const member function is inherently capable of doing whatever it does to its object, so invoking a const member function is also correct).

The

Two functions are assumed to be only constant (one is a const member function and one is a non-const member function). can also be overloaded. as a good programming style, when declaring a member function, if the member function is not the correct data member to make a change operation, the member function should be declared as const  member function whenever possible. c++ const const class object called. declaring a member function as const guarantees that the member function does not alter the data member. However, assuming that the member is a pointer, the const member function does not guarantee that the object pointed to by the pointer is not altered, and the compiler will not detect such a change as an error.

int foo (int *test) const; //Can be seen as: int foo (const A *this,int *test);  


6,Constwith theDefine

Const -modified constants are determined during compilation. Const constants are handled by the compiler, providing type checking and scope checking, and macro definitions handled by the preprocessor. Simple text substitution.

void Fun1 () {    #define A,    const int b =;    #undef a  //the macro defines a unload, limit scope} void Fun2 () {    printf ("a =%d\n", a);    printf ("B =%d\n", b);   


7,Constwith theconstexpr

constexpr: constant expression, which is the expression that the value does not change and can be evaluated during compilation.

is determined by both the data type and the initial value.

   const int max =;         Max is a constant expression   const INT-limit = max + 1;   Limit is a constant expression   int size =;               Size is not a constant expression, just a normal int type   const int sz = Get_size ();   SZ itself is a constant, but its value is determined by the ability to execute, so it is not    a constant expression generally speaking, suppose you assume that a variable is a constant expression. Then declare it as a constexpr type.

const int SZ = Get_size (); Only Get_size () is a constexptr function. is the correct declaration statement.


8,Constwith theAuto

auto usually ignores the top-level const. At the same time, the underlying const is preserved.

void Main () {   //auto usually ignores the top-level const, while the underlying const is preserved at the same time.

int i = ten; const int CI = i; const int &CR = CI; Auto B = ci; b is an int (the top-level const attribute of CI is ignored) auto C = cr; c is an int (CR is the alias of CI, the top-level const attribute of CI is ignored) auto d = &i; D is an integer pointer (the address of an integer is a pointer to an integer) auto e = &ci; E is a pointer to an integer constant (the address of a constant object is an underlying const) //Assuming that the auto type you want to determine is a top-level const. It is necessary to understand that the const auto f = ci; The deduction type of CI is int,f is const //can also set the reference to auto, the original initialization rule still applies to auto &g = ci; G is a constant reference. Bind to CI //auto &h =; Error: Obviously you cannot bind a lot of references to a literal value.

(What do you say?) H is a reference to 42? Literal 42 no memory space no way to make a reference) const auto &J =; Correct: Ability to reference binding literals for constants}


9,Constwith theDecltype

Decltype handles top-level const and references in a different way than auto . Assuming that the expression used by Decltype is a variable, decltype Returns the type of the variable.

  int i = 10;const int ci = i;const int &cr = Ci;decltype (ci) x = 0;    The type of x is the const intdecltype (cr) y = x;    The type of y is const int&. Y is bound to X//decltype (CR) Z;      
10, const and iterators

vector<int> vec;const vector<int>::iterator ite = Vec.begin ();         ITE equivalent to tx  const*ite = ten;                                                                    Correct, change the object that ITE refers to ++ite;                                                                          Error, ITE is the const vector<int>::const_iterator conite = Vec.begin (); Conite equivalent to const  tx*conite = ten;                                                             Error, Xconite is a const ++conite;                                                                   Correct, change conite

Overview 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.