Summary of C + + const usage (welcome everyone to make bricks)

Source: Internet
Author: User
Tags volatile

C++const Keyword Summary

Const is the abbreviation of constant , the meaning of which is invariable and not easy to change .

Const is used in C + + to decorate a built-in type variable, custom object, member function, return value, function parameter .

A const modifies a variable of a common type.

As follows:

1 const int  a = 7; 2 3 int  B = A;//it ' s right4 5 a = 8;       It ' s wrong,

A is defined as a constant and you can assign a to B, but you cannot assign a value to a again. Assigning a value to a constant is illegal because A is considered by the compiler to be a constant whose value is not allowed to be modified.

Then look at the following actions:

1   2  3 #include <iostream> 4  5 using namespace std; 6  7 int main (void) 8  9 {Ten-one     const INT
   a = 7;12     int  *p = (int*) &a;14, *p     = 8;16 cout<<a;18     System ("pause"); 21
   return 0;22 23}

For const variable A, we take the address of the variable and convert it to a pointer to int , then use *p = 8, re-assign the value in the variable a address, and then output to view the value of a.

From the debug window below, see that the value of a is changed to 8, but the output is still 7.

As we can see from the results, the compiler then thinks that the value of a is at the beginning of the definition of 7, so the operation on Const A will produce the above situation. So don't try to assign a value to a const variable easily, which can create unexpected behavior.

If you do not want the compiler to perceive the above-to-const operation, we can add the volatile keyword before the const

The volatile keyword is the opposite of const, which is variable and easy to change . So it is not optimized by the compiler, and the compiler does not change the operation of the A variable.

1 #include <iostream> 2  3 using namespace std; 4  5 int main (void) 6  7 {8  9     volatile const INT
   a = 7;10     int  *p = (int*) &a;12 = *p     = 8;14 cout<<a;16     System ("pause"); 19
   return 0;20 21}

The output, as we expected, is 8.

Second, the const modifier pointer variable.

The const modifier pointer variable has the following three cases.

A:const the content that the pointer points to, the content is not variable.

B:const modifies the pointer, the pointer is not variable.

C:const modifies the contents of pointers and pointers, the pointers and pointers to the contents are non-variable.

For a:

1 const int *p = 8;

The pointer to content 8 cannot be changed. The abbreviation is left fixed because the const is on the left side of the * number .

For B:

1  int a = 8;2  3  int* const P = &a;4 5  *p = 9;//it ' s RIGHT6 7  int  b = 7;8 9  p = &b;/ It ' s wrong

The memory address pointed to by the const pointer p cannot be changed, but its contents can be changed. Short, right-oriented . Because the const is on the right side of the * number .

For C:

Is the merger of A and B,

1 int a = 8;2 3 const int * Const  p = &a;4 5  

At this point, the contents of const p and the memory address pointed to are fixed and immutable.

For a,b,c three cases, depending on the position of the const in the * number, I summarize three sentences to facilitate memory,

"left, right-oriented, const-modifier invariants".

Third, const parameter passing and function return value.

There are three cases for the const modifier function parameter.

A: The const adornment pass for value passing, generally this situation does not require a const adornment, because the function automatically produces the temporary variable copy argument value.

1 #include <iostream> 2  3 using namespace std; 4  5 void CPF (const int a) 6  7 {8  9     cout<<a;     ++a//;  It's wrong, a can ' t is changed12,}14 int main (void), (     8);     System ("pause");     Turn 0;24 25}

B: When the const parameter is a pointer, you can prevent the pointer from being accidentally tampered with.

1 #include <iostream> 2  3 using namespace std; 4  5 void Cpf (int *const a) 6  7 {8  9     cout<<* a<< "";     *a = 9;12}14 int main (void): {+]     int a = 8;20     Cpf (&a);     t;<a; A is 924     system ("pause");     return 0;28 29}

C: Parameter passing of custom type, need temporary object copy parameter, for the construction of temporary object, need to call constructor, compare waste time, so we take the method of const plus reference passing.

and for the general int, double and other built-in types, we do not use the reference delivery method.

1 #include <iostream> 2  3 using namespace std; 4  5 class Test 6  7 {8  9 public:10 one     Test () {}12 1 3     Test (int _m): _cm (_m) {}14     int get_cm () const16 ~        _cm;20 +}22 private:24     C10/>int _cm;26};28  void Cmf (const test& _TT) (cout<<_tt.get_cm)     ; 36 37}38 39 int main (void), Max. (     8),     CMF (t),     system ("pause"), and     return 0;50 51}

Result output 8

For the return value of the const modifier function

The const modifier returns a value of three cases.

The A:const modifies the return value of the built-in type, and the adornment acts as a non-decorated return value.

1 #include <iostream> 2  3 using namespace std; 4  5 const int CMF () 6  7 {8  9     return 1;10 11}12 1 3 int Cpf () () [0;18]     2 int main (void)     : [_m] = CMF (),     int _n = CPF (); 8     cout<<_m<< "" <<_n;32     System ("pause");     return 0;36 37}

The b:const modifies the custom type as the return value, at which point the returned value cannot be used as an lvalue and cannot be assigned or modified.

C:const modifies the returned pointer or reference, returns a pointer to the const, depending on what we want the user to do.

The Const modifier class member function.

The Const modifier class member function is designed to prevent member functions from modifying the value of the called object, and if we do not want to modify the value of a calling object, all member functions should be declared as Const member functions. Note: The Const keyword cannot be used in conjunction with the static keyword because the static keyword modifies a static member function, which does not contain the this pointer, that is, the const member function must be specific to an instance.

The following get_cm () const; The function uses the const member function

1 #include <iostream> 2  3 using namespace std; 4  5 class Test 6  7 {8  9 public:10 one     Test () {}12 1 3     Test (int _m): _cm (_m) {}14     int get_cm () const16 ~ _cm;20 +}22     25     int _cm;26};28-  void Cmf (const test& _TT) (     36 37 cout<<_tt.get_cm 3) 9 int main (void), Max. (     8),     CMF (t),     system ("pause"), and     return 0;50 51}

If GET_CM () removes the const modifier, the const _TT passed by the CMF, even if it does not change the value of the object, is considered by the compiler to change the value of the object, so we try to make all functions that do not need to change the contents of the object as a const member function as required.

What if there is a member function that wants to modify one of the members of an object? at this point we can use the mutable keyword to modify the member, mutable meaning is also variable, easy to change the meaning of the mutable keyword modified members can be in the changing, such as the following example.

1 #include <iostream> 2 using namespace std; 3 class Test 4 {5 public:6     test (int _m,int _t): _cm (_m), _ct (_t) {} 7     void Kf () const 8     {9         ++_cm;//it ' s WR Ong10         ++_ct;//it's right11     }12 private:13     int _cm;14     mutable int _ct;15};16 int main (void) 18 {19< C13/>test T (8,7);     return 0;21}

Here we pass the ++_ct in Kf () const , modify the value of the _CT, but change the _cm by ++_cm error. Because ++_cm is not decorated with mutable .

Summary of C + + const usage (welcome everyone to make bricks)

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.