The const of C + +

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 run 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. the const variable in the C language is a read-only variable with its own storage space. the C + + compiler handles const by: When a constant declaration is encountered, in the "Symbol table" (C + + compiler specifically set) to put a constant in the use of a when using the symbol table directly in the value! So the question is, how do you 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 beused in other files) or the & operator is found for Const during the compilation process , give the const constant is also allocated specifically for storage space.


as shown, after taking the address of the const variable,The space is allocated separately for "a", but not with a in the symbol table .

2,Constwith the underlying data type:

   the const int bufsize = 512;bufsize value can no longer be modified, and any attempt to assign a value to BufSize throws an error. Const objects must be initialized because the const object cannot be changed once it has been created.   int i=12;const int ci=i; You can also take advantage of another object (which is not const) to initialize the const object ... int j = CI; Once the copy is complete, the new object has nothing to do with the original object. {   int i =;   const int J = i;      Initialize   int k = j;   int m = +;   j = m;              Assignment, compilation Error}

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

If a const object needs to be shared on a different file, you need to add the extern keyword to the const object, whether it is a declaration or a definition .

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

Declare directly when used:extern const int bufsize; no longer defined, otherwise an error occurs. extern shows that bufsize is not unique to this file, 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: References and their corresponding objects are constants//ri = 100;      Error:ri is a reference to a constant//int &r2 = CI;    Error: To point a very important reference to a constant object, if correct, then you can modify the R2 to change the value of CI, ci obviously can not change.   Constant references allow to be bound to very much objects, literals, general expressions ———— Exceptions 1 int i = 50;        const int &AMP;CRI1 = i;      The object const int &AMP;CRI2 = 500;    literal value const int &AMP;CRI3 = i * 2;          General expression int r4 = CRi1 * 2;   Correct: The constant feature of CRI1 only works when the change is performed, the copy assignment does not change, and once the copy is complete, the new object and the original object have no relation.        int &AMP;R5 = CRI1 * 2;          Error: to point to a constant object, if correct, you can change the value of CRI1 by modifying the R5, CRi1 obviously cannot change.             /* * * * * * * * * * * * * In general, the referenced type must match the type of the object it refers to.             * What happens when a constant reference is bound to another type?                 * Double d = 3.14;              const int &ri = D;   * CONST INT TMP = D;   A temporary integer constant const int &ri = d is generated by a double-precision floating-point number; Let ri bind this temporary constant * * * * * * * * * * *//constant reference only limits the actions that you can participate in, and if the referenced object is a very mass, then allow other ways to change its value INT J = 10;             int &AMP;RJ = j;       Reference RJ Binding Object J Const int &AMP;CJ = j;               The constant reference to CJ also binds the object J, but does not allow the value of the J to be modified via CJ RJ = 1000;   Modified by RJ J,j is modified to//CJ = 1000;   cout << "J:" << J << ", CJ:" << CJ << Endl;   j:1000, cj:1000}

4,Constwith the pointer

pointers or references to constants are merely pointers or references to "self-righteous", and they feel themselves pointing to constants, so they consciously do not change the value of the object it points to. (But a constant pointer or reference can point to a very good amount, and the very amount can be changed by other means.)

Pointers are objects, and references are not! Therefore, the pointer itself is not 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!

The 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, any attempt to assign a value to B 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 (the memory data pointed to cannot be modified, but can be modified by itself) const int *C1 = &ci;        int *C2 = &ci;          The address that holds the constant, only the pointer to the constant 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 allowed to be modified (the underlying const), modify the direction of C, and 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 modified, but it points to the memory space can be modified) int II = 0;    int * Const D =?               D will always point to II (top-level const), does not allow to modify the value of D *d = 250; The pointer itself is a constant and does not mean that you cannot modify the value pointed to by the pointer.     (depending on the object to which it is directed) cout << II << Endl;    II is modified to a number, (d points to a very good amount)//fifth E a pointer to the constant shape of the constant (pointer and the memory space it points to, can not be modified) 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. Two functions can be overloaded if they are just a constant difference.

6,Constwith theDefine

Const -modified constants are determined during compilation. Const constants are handled by the compiler, providing type checking and scoping checks, and macro definitions handled by the preprocessor, with 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, only a normal int type   const int sz = Get_size ();   SZ itself is a constant, but its value is not determined until run time, so it is not a constant expression    generally speaking, if you decide that a variable is a constant expression, declare it as a constexpr type.   const int SZ = Get_size ();   Only Get_size () is a constexptr function, which is the correct declaration statement.

8,Constwith theAuto

Auto generally ignores the top-level const, while the underlying const is preserved.

void Main () {   //auto generally ignores the top-level const, while the underlying const is preserved.   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 a low-level const)    //////If the auto type you wish to infer is a top const, you need to explicitly indicate 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, bound to ci   //auto &h =;        Error: Obviously you cannot bind a very literal reference to a literal. (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: You can reference bound literals for constants}

9,Constwith theDecltype

Decltype handles top-level const and references in a different way than auto . If 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 the const int&,y bound to X//decltype (CR) Z;      

The const of C + +

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.