C + + const modifier pointers

Source: Internet
Author: User

when const encounters a pointer

In general, the const modifier pointers can be divided into the following concentration cases.

Describe Example Meaning Note
Const on the left of *

const INT *b=&a;

int const *b=&a;

The const modifier pointer points to a variable, which means that we cannot modify the pointer B by

Point to the value to modify a. that is, *b=100; This operation is wrong.

At this point, pointer B itself is not a constant, *b is a constant.

In this case, if you want to modify the value returned by the *b, it is possible to modify the object referred to by pointer B in two ways:

· Change the value of the variable A that the B points to, a=100;

• Let b point to another variable, int c=100; b=&c;

Const on the right of * int* Const b=&a;

The const modifier pointer, which means that attempting to change the value of B is wrong. Such as:

b++; ++b, such operations are all wrong.

At this point, pointer b itself is a constant, *b is not a constant.

Since pointer b is a constant, it must be initialized when she is created, or it will go wrong.
* The left and right sides have a const Const int* Const b=&a; Both the pointer itself and the contents of the pointer are constants.

To put it another point, when C + + defines a class, if there is a function inside the class we want it to not modify the member variables inside the class, and after the parameter list of the function a const can tell the compiler that the function does not modify the member variables inside the class. But you want the function to have this effect on only a subset of member variables, and you can modify the member variable in the const function by adding a mutable to the member variable that you can modify.

C + + const modifier pointers

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.