Summary of const usage in C + +

Source: Internet
Author: User

The use of const in C + + is very wide, the meaning of the use of different locations is not the same, so want to write an article to do a summary.


First, it is clear that const is the basic meaning of "unchanging", but it does not mean that nothing is changed, as you will see below.


1. Const and variable

Basic principle: Const variables (objects) cannot be modified

The introduction of const in the variable is related to the magic number, so-called "magic number" refers to a sudden occurrence of a constant value (also called literal value constant).

for (int i = 0; i < i++) {//Todo}

in the above example, 512 is the magic number, 512 suddenly appear in the loop, it is impossible to know its meaning, so the introduction of Const.

const int length = 512;for (int i = 0; i < length; i++) {//Todo}

This means that the loop is within the length range.



1.1 Const modifies a variable (or object) so that it becomes a constant, indicating that the value of the variable can no longer be modified, because of this, it must be initialized when a constant is defined.


Scope of the 1.2 const constant:

We know that a variable is declared within the global scope (especially a variable that is not const-modified), which acts on the entire program and can also be referenced in other files because it declares a variable in the global scope, which is extern-decorated by default.

Declares a const variable in the global scope, which is not extern-decorated by default, so it can only be used in this file, and to be accessed in other files, it needs to be explicitly declared as extern




2. Const and references

Basic principle: A const reference is a reference to a const variable (object)
const int ival = 1024;const int &refval = ival;


2.1 Const Reference can point to a const variable of a related type (not this type)

Double dval = 3.14;const int &refval = Dval;

The compiler converts a double to a temporary int object and then binds the const reference to the temporary object, so changing the value of Dval does not change refval, that is, Dval is still a non-const variable, and refval is still a constant reference.

Primer Fourth Edition is the above statement, but I in the VS2012, the const can also point to a non-const variable of this type, the reason for finding the data is probably to meet the reference-campatible condition.

Theoretically, we should strictly abide by the constant reference to the constant object, the very volume reference to the very object, to avoid errors.


3. Const and pointers

There are two types of const-pointer relationships: A const-decorated pointer and a pointer to a const object, where the const position is not the same


3.1 Pointer to const object (const in front of pointer symbol *)

for a const object, you must point to it with a pointer to the const. The reason is that the const modifier prevents the object from being altered, and if the pointer is not a pointer to a const, it can be modified by a pointer, which is not allowed.
const int ival = 1;const int *ptrval = &ival;


Conversely, for a pointer to a const object, you can point to any object, how do you understand that? Let's first look at the process of pointer assignment:
int *ptr = &val;

The address of Val is assigned to PTR because the assignment is only an address, so it is not known whether the object pointed to by PTR is a const value.

If we assign an address to a pointer to const, then the pointer thinks it is a const object, that is, the PTR pointer points to an object that is "self-considered" as Const.
int ival = 1;const int *ptrval = &ival;


The above procedure is correct, we need to make it clear that ival is a non-const variable, so we can change the value of ival by assigning a value to Ival. Ptrval points to a self-considered const object, so we cannot change the value of Ival by *ptrval.


3.2 Const-Decorated pointer (const is behind pointer symbol *)

int *const ptr;

a pointer to a const type is declared above, meaning that the pointer itself is a constant and cannot be modified.


How to understand? the value of the pointer itself is an address, if the pointer itself is a constant, then the address value cannot be modified, that is, the pointer can only point to this address, cannot point to other places. But the content of the address pointed to by the pointer does not belong to the value of the pointer itself, so the content it points to can be changed.
int ival = 1;int *const ptr = &ival;*ptr = 2;     Okint ivaltwo = 11;ptr = &ivaltwo//Error


In summary, you can define a const pointer that points to a const object

const int *const ptr = &ival;


Error-prone const pointer in 3.3 typedef

typedef string *ptr;const ptr s_ptr;

The *s_prt cannot be directly substituted as a const string, so s_ptr is a pointer to a const string.
First, PTR is a pointer, and the const modifier is a pointer, so it should be a string *const s_ptr; s_ptr is a const pointer to string.



4. Const and Array

The const and array point is that the const must initialize this principle when defined, so when using a dynamically allocated array, if the array stores objects of the const type, it must be initialized (using the initialization symbol ()).



5. const and function return value

The return value of the modifier function that returns a constant.
const int foo ();

5.1 Returns passed by value

If the function returns with value passing, such as returning an int type, then the function copies the returned value (for example, 47) to an external temporary storage unit (resulting in a temporary copy), so the Const modifier makes no sense
int foo (); const int foo ();

The two are exactly the same. It is important to note that value passing produces a temporary copy, which is inefficient (as in the following const and function arguments), so it is usually returned by reference passing.


5.2 Returns passed by reference (not much see)

If the return value is not an intrinsic type, a reference pass is typically used to return the result because the reference is passed by itself and no temporary copy is required. However, it is important to note that only one alias is returned at this time.
ClassType &foo (); const ClassType &foo ();

The const-decorated return reference value, which indicates that the result of a function call can only be assigned to a const reference of the same type.



5.3 Returns passed by pointer
Const ClassType *foo ();

The representation function returns a pointer to a ClassType type that points to a const object, which cannot be modified, so the return value of the function can only be assigned to a pointer of the same type that points to a const.
Const ClassType *PTR = foo (); Okclasstype *ptr = foo (); Error


6. Const and Function parameters

First, it needs to be clear that the purpose of the Const modifier is to protect the modified content from being changed.
In C + +, function parameters are divided into value passing, pointer passing, and reference passing.


6.1 Value Pass

value passing produces a temporary copy of the function call, and the modification and operation of the incoming parameter in the function is an operation on the copy, without changing the value of the argument itself, so no const is required to protect it.

The protection of value passing is very good, but the value passing has the disadvantage, needs to produce the temporary copy, if passes in the object, then needs constructs, the copy, and the destruction and so on operation, the efficiency is not high. This can be considered as reference passing

void foo1 (int x); void Foo2 (ClassType instance); Higher overhead


The following protection does not make sense:


6.2 Reference Delivery

reduce overhead by passing in references to actual parameters. Because the reference itself, there is no need to produce a temporary copy .
void foo1 (int &x); void Foo2 (ClassType &ref);

for both functions, the function call is exactly the same as the value pass, unlike the X and ref that are obtained inside the function are references that invoke the incoming arguments. Because of this, the reference can change the arguments passed in by the function to change the argument. This is dangerous for the actual argument, which requires a const modifier to protect the incoming reference from being modified.
void foo1 (const int &x); void Foo2 (const ClassType &ref);

Generally speaking, there is no such thing as the construction of the object for the basic internal type, so the following two kinds of protection parameters are not modified in the same way as the efficiency basically.
void foo1 (int x); void foo1 (const int &x);


6.3 Pointer passing

Pointer passing is the same as a reference pass when the protection parameter is not modified, and a function of pointer passing is to expand the range of receive parameters:
void foo1 (const ClassType *ptr);


Combining the above const with the pointer, we know that PTR points to a self-considered const type object, so! The incoming object is not necessarily a const-decorated object, it can be a const object, or it can be a non-const object. Conversely, you can only pass in non-const objects if there are no formal parameters for the const modifier function.

It is necessary to be clear that, regardless of whether a const object is passed in, the object cannot be modified by a pointer, which is consistent with the const relationship of the pointer above.


Finally, you need to know that const can only modify one input parameter, and if it is an output parameter, whether it is a reference pass or a pointer pass, you cannot use const to decorate


7. Const and data members of a class

Const-Decorated data members cannot be initialized in constructors and can only be initialized with a member initialization list.
My understanding is that because the data member is initialized with a member initialization list before the constructor executes, it is not allowed to initialize the data member in the constructor, which is equivalent to assigning the const two times.


The reason for this is that you can refer to the initialization of a reference type in a class, and you must initialize it in the initialization list, because the reference type must also be initialized at the time of definition, requiring the same as const, so both can only be initialized with the member initialization list.


8. Const and member functions of a class

in the const member function, the const is located after the function's argument list (the function declaration precedes the function's return value is a constant)


The const-Decorated member function indicates that the member function is a read-only function and does not change the member variable.
The real meaning of the const member function is that the const actually modifies the member function to be the implied parameter of the this pointer, which means that the const ClassType *this is passed in, because this is pointing to a const object, so it cannot be modified.


Because this is a pointer to an object, we need to combine the const and pointer knowledge again:

(1) const modifies this, gets const ClassType *this,this points to a "self-think" is a const object (that is, itself), so any object (const or non-const) Can call a const member function because the incoming pointer considers itself as a const object, so it cannot be modified.


(2) For a const object, when it calls a member function, the default is to pass the this pointer parameter, because this is pointing to a const object (itself), so the equivalent member function is const decorated, the member function is a const member function, so conversely, A const object can only call a const member function because a non-const-decorated member function is not a pointer to a const object.


(3) in 8.2 of the basic, further, each member function can call other member functions, each member function passed the this pointer, so the member function calls each other must maintain the consistency of this pointer, so the const member function can only call the const member function, because both of the incoming this pointer is a const fix Decorated. For non-const member functions, the this pointer is passed in non-const adornments, so it cannot be called.


understand the true meaning of const, be sure to keep the const member function passed in the const pointer of the consciousness, the object invocation needs to see whether the object (itself, pointer, reference) is a const.

Summary of const usage in 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.