Analyze c++ const Pointers and Pointers to const in detail

  • 2020-10-23 20:15:08
  • OfStack

Recently in the review of C++, pointer this is really a difficult point, for a long time did not pay attention to, tonight a good summary of 1 const pointer, for a long time no blog, record 1 ~

Definition of const pointer:

const pointer is the value of pointer variable 1. After initialization, the pointer cannot be changed. Initialization is necessary. Its definition is as follows:

[

type *const pointer name;

]

When a pointer is declared, the keyword const can be used before or after the type, or both. For example, the following are all legitimate declarations, but with very different meanings:

[

const int * pOne; // A pointer to an integer constant, which points to a value that cannot be modified

int * const pTwo; // A constant pointer to a shape. it cannot point to another variable, but its value can be modified.

const int *const pThree; // A constant pointer to an integer constant. It can no longer point to any other constant, nor can it change the value it points to.

]

The trick to understanding these declarations is to look to the right side of the keyword const to determine what is declared as constant, and if the right side of the keyword is type, then the value is constant; If the right side of the keyword is a pointer variable, the pointer itself is constant. The following code helps illustrate this point:


const int *p1; //the int pointed to is constant

int * const p2; // p2 is constant, it can't point to anything else

const pointer and const member functions

You can use keywords for member functions. Such as:


class Rectangle

{

  pubilc:

  .....

  void SetLength(int length){itslength = length;}

  int GetLength() const {return itslength;} // Member functions are declared as constants 

  .....

  private:

  int itslength;

  int itswidth;

};

When a member function is declared as const, the compiler will treat it as an error if it attempts to modify the object's data.

If a pointer to an const object is declared, only the const method (member function) can be called through that pointer.

The example declares three different Rectangle objects:


Rectangle* pRect = new Rectangle;

const Rectangle * pConstRect = new Rectangle;  // Point to the const object 

Rectangle* const pConstPtr = new Rectangle;// pConstRect Is pointing to const Pointer to an object that can only be declared as const Is a member function of, such as GetLength (). 

The const pointer and the pointer to const

There are two meanings when using a pointer with const. One is that you cannot modify the contents of the pointer itself, and the other is that you cannot modify the contents of the pointer. It sounds a little confusing but I'll show you an example.

Let's start with a pointer to const, which means that the pointer points to something that cannot be modified. There are two ways to write it.

[

const int* p; (recommended)

int const* p;

]

The first can be understood as p is a pointer to the content of the const int type. p itself can point to any identifier without initializing it, but what it points to cannot be changed.

The second one can be easily interpreted as p is an const pointer to int (the pointer itself cannot be modified), but this is wrong. It also means a pointer to const (the pointer cannot be modified), which means the same as the first one. The first one is recommended to avoid confusion.

The const pointer means that the value of the pointer itself cannot be changed. There's only one way to write it

[

int* const p=1 address; (Since the value of the pointer itself cannot be modified, it must be initialized)

]

This form can be understood as p is a pointer to the const pointer to int. It points to values that can be changed *p=3;

There is also a case where the pointer itself and what it points to cannot be changed. See below.

[

const int* const p=1 address;

int const* const p=1 address;

]

Read the above content is not a little dizzy, it doesn't matter, you don't have to back it, with more will know, there is a skill, through the above observation we are not difficult to sum up 1 point rule, what is it? The rule is: pointer to const (pointer to content cannot be modified) const key words always appear on the left side of the * and const pointer (the pointer itself cannot be modified) const always appear on the right side of the * key words, needless to say that two const add a * must be the content of the pointer itself and its direction is cannot be changed. With this rule is not to remember more.


Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> 1 #include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
 int a=3;
 int b;
 
 /* Definition to const Pointer to (the contents of the pointer cannot be modified) */ 
 const int* p1; 
 int const* p2; 
 
 /* define const Pointer to the ( Since the pointer itself cannot be changed, it must be initialized.) */ 
 int* const p3=&a; 
 
 /* The pointer itself and what it points to cannot be changed so it has to be initialized */
 const int* const p4=&a;
 int const* const p5=&b; 
 
  p1=p2=&a; // correct 
  *p1=*p2=8; // Incorrect (the pointer to something that cannot be modified) 
 
  *p3=5; // correct 
  p3=p1; // Incorrect (the pointer itself cannot be changed)  
 
  p4=p5;// Is not correct   (The pointer itself and what it points to cannot be changed.)  
  *p4=*p5=4; // Incorrect (the pointer itself and what it points to cannot be changed)  
  
 return 0; 
}

const:

const is most commonly used to define constants. In addition, it can modify function parameters, return values, and function definition bodies.

1. const modifies the parameters of the function

If the parameter is used for output, no matter what data type it is, and no matter if it is "pointer pass" or "reference pass", it cannot be modified with const, otherwise the parameter will lose its output function.

const can only modify input parameters:
If the input parameter is "passed by pointer", the const modifier protects against accidental changes to the pointer.
Will "const & The usage of the modified input parameter is summarized as follows:

(1) For input parameters of non-internal data types, the way of "value passing" should be changed to "const reference passing" in order to improve efficiency. For example, void Func(A a) is changed to void Func(const A) & a).

(2) For input parameters of internal data types, do not change the mode of "value passing" to "const reference passing". Otherwise, it can not achieve the purpose of improving efficiency and reduce the understandability of the function. For example, void Func(int x) should not be changed to void Func(const int) & x).

2. const modifies the return value of the function

If const modifiers are added to the "pointer passed" function return value, the contents of the function return value (that is, the pointer) cannot be modified, and the return value can only be assigned to the same type of pointer as the const modifier. Such as function

[

const char * GetString(void);

]

The following statement will cause a compilation error:

[

char *str = GetString();

]

The correct usage is

[

const char *str = GetString();

]

If the return value is not an internal data type, rewrite the function A GetA(void) to const A & GetA(void) does improve efficiency. But be careful, 1 must know whether the function wants to return a copy of an object or just an alias, otherwise the program will make an error.
There are not many occasions when the return value of a function is "passed by reference". This method is usually only used in the assignment function of a class for the purpose of chain expression.
Such as:


class A
{
A & operate = (const A &other); //  The mutator 
};
A a, b, c; // a, b, c  for A  The object of 
a = b = c; //  Normal chain assignment 
(a = b) = c; //  Improper chain assignment, but legal 

If the return value of an assignment function is modified with const, the contents of the return value are not allowed to be altered. In the above example, the statement a = b = c is still correct, but the statement (a = b) = c is illegal.

3. const modifies member functions

A few rules about the Const function:

const objects can only access const member functions, and non-const objects can access any member function, including const member functions. The members of the const object are not modifiable, whereas objects maintained by the const object through Pointers are modifiable. const member functions cannot modify the data of an object, regardless of whether the object has const properties. It checks at compile time based on whether the member data has been modified or not. The data member with the mutable modifier, however, can be modified by any means under any circumstances, and naturally the const member function can be modified at this point

Above is the detailed analysis of c++ const Pointers and Pointers to const details, more information about c++ const Pointers please pay attention to other related articles on this site!


Related articles: