A summary of the common usage of the Const keyword in C + + programming _c language

Source: Internet
Author: User
Tags modifier

1. Defining constants
(1) The const modifier variable, the following two kinds of definition form are essentially the same. It means that the variable value of the type with the Const modifier is immutable.

 TYPE const VALUENAME = value; 
  Const TYPE VALUENAME = value;


(2) Change the const to an external connection for expansion to global, the memory is allocated at compile time, and can be uninitialized, just as a declaration, which the compiler considers to be defined elsewhere in the program.

  Extend const int valuename = value;

2, the use of const pointer
(1) The pointer itself is a constant variable

  (char*) const pcontent; 
  Const (char*) pcontent; 

(2) What the pointer points to is a constant variable

  Const (char) *pcontent; 
  (char) const *pcontent; 

(3) Both are not variable

  const char* Const pcontent; 

(4) There are also different ways to draw a line along the * number:
If the const is on the left side of the *, the const is used to modify the variable that the pointer points to, that is, the pointer to a constant;
If the const is on the right side of the *, the const is the cosmetic pointer itself, that is, the pointer itself is a constant.

3. Use const in function

(1) const modifier function parameters
A. Passing parameters cannot be changed within a function (meaningless because Var itself is a formal parameter)

void function (const int Var);

B. The parameter pointer refers to a constant variable

void function (const char* Var);

C. The parameter pointer itself is a constant variable (and meaningless because char* var is also a formal parameter)

void function (char* const VAR);

D. parameter as reference, in order to increase efficiency and prevent modification. When a reference parameter is decorated:

void function (const class& Var); A reference parameter cannot change a void function

(const type& Var) within a function;//reference parameter is constant in a function

Such a const reference pass is exactly the same as the most common function passed by value, and he prohibits all modifications to the referenced object, except that passing by value will first create a copy of the class object and then pass the past, and it passes the address directly, So this transfer is more efficient than passing by value. In addition, only a reference const pass can pass a temporary object, because the temporary object is a const attribute and is not visible, he has a short time in a local domain, so cannot use the pointer, only the reference of the Const pass can catch this guy.


(2) const modifier function return value
The const modifier function returns a value that is not very useful, and its meaning is essentially the same as the const-modified ordinary variable and the meaning of the pointer.

 A.const int fun1 ()//This is actually meaningless because the parameter return itself is an assignment.
 B. const int * FUN2 ()//call when const int *pvalue = FUN2 (); 
       We can think of fun2 () as a variable, that is, the contents of the pointer are immutable.
 c.int* Const FUN3 ()//Call time int * Const PVALUE = fun2 (); 
       We can think of fun2 () as a variable, that is, the pointer itself is immutable.

In general, when a function returns a value of an object, it is used for overloading the operator if it is declared as Const. Generally, it is not recommended to use the Const modifier return value type of a function as an object or as a reference to an object. The reason is as follows: If the return value is a const (const a test = a instance) or a reference to an object is const (const a& test = A instance), the return value has a const attribute. The return instance can only access public (protected) data members and const member functions in Class A and does not allow assignment operations, which is rarely used in general.


4, class-related const

(1) const modifier member variable
The const modifier member function of a class, which represents a member constant, cannot be modified, and it can only be assigned a value in the initialization list.

 Class A
 { 
  ...
  .. const int Nvalue;   Member constants cannot be modified ...
  A (int x): Nvalue (x) {}; You can only assign values in the initialization list
  } 

(2) Const modified member function
Const modifies a member function of a class, the member function cannot modify any of the non-const member functions in the class. Generally written at the end of the function to decorate.

 Class A
 { 
  ...
  .. void function () const; A constant member function that does not change the member variables of an object.      

Nor can you call any of the non-const member functions in the class.
}

For a Const class object/pointer/reference, only the const member function of the class can be invoked, so the most important function of the Const modifier is to restrict the use of the const object.

A. A const member function is not allowed to modify any of the data members of its object.

B. A const member function can access a const member of an object while other member functions are not available.

(3) Const modifier class object/object pointer/object reference

· The const-Decorated class object represents the object as a constant object in which no member can be modified. The same is true for object pointers and object references.

· The const-decorated object, any non-const member function of the object, cannot be invoked because any non-const member function has an attempt to modify the member variable.
For example:

Class AAA
{ 
 void func1 (); 
void Func2 () const; 
Const AAA Aobj; 
Aobj.func1 (); x
aobj.func2 (); correct

const aaa* aobj = new AAA (); 
Aobj-> func1 (); X
aobj-> Func2 (); correct


5, using the const modifier function parameters
If the parameter is output, no matter what data type it is or whether it uses "pointer pass" or "reference pass", it cannot be modified with the const, otherwise the parameter loses its output function. Const can only modify input parameters:
If the input parameter is "pointer pass", the addition of the const modifier prevents the pointer from accidentally changing, which is a protective action.
For example, the Stringcopy function:

void Stringcopy (char *strdestination, const char *strsource);

Where strsource is an input parameter, strdestination is an output parameter. After adding a const modifier to the strsource, the compiler will point out an error if the statement in the body of the function attempts to change the contents of the strsource.
If the input parameter is passed by value, the input parameter is inherently unprotected because the function automatically generates a temporary variable to copy the parameter, so do not add a const modifier.
For example, do not write a function void Func1 (int x) as a void Func1 (const int x). Similarly, do not write the function void Func2 (a) as a void Func2 (const a). Where a is a user-defined data type.
for parameters that are not intrinsic data types, functions such as the Declaration of Void Func (a) are destined to be more efficient than the bottom. Because the body of a function will produce a temporary object of type A to copy parameter A, the construction, replication, and destructor of the temporary object will consume time.
to improve efficiency, you can change the function declaration to void Func (A &a), because reference passing only borrows the alias of the argument and does not need to produce a temporary object. However, there is a disadvantage to the function void Func (a &a):
Reference passing may change parameter A, which we do not expect. It is easy to solve this problem by adding a const modifier, so the function eventually becomes void Func (const A &a).
and so on, should void Func (int x) be rewritten as void Func (const int &x) to increase efficiency? Absolutely unnecessary, because the parameters of the internal data type do not have a construction, a destructor, and replication is very fast, and the efficiency of value passing and reference passing is almost equal.
The problem is so lingering that I have to summarize the usage of the "const &" modifier input parameter.
 
For input parameters that are not internal data types, you should change the way value is passed to const reference delivery to increase efficiency. For example, change void Func (a) to void Func (const a &a).
 
For input parameters for internal data types, do not change the way value is passed to const reference delivery. Otherwise, it can not achieve the goal of improving efficiency, but also reduce the comprehensible function. For example, void Func (int x) should not be changed to void Func (const int &x).

6, using the const modifier function return value
If you modify the function return value with the "pointer Pass" method, 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 with the const modifier. such as functions

const char * GetString (void);

The following statement will present a compilation error:

Char *str = GetString ();

The correct usage is

const char *STR = GetString ();

If the function return value is in "value delivery", the const modifier has no value because the function copies the return value to an external temporary storage cell.
For example, do not write the function int GetInt (void) as a const int GetInt (void).
Similarly, do not write function a geta (void) as const a geta (void), where a is a user-defined data type.
If the return value is not an intrinsic data type, rewriting function a geta (void) to const A & Geta (void) does improve efficiency. But you must be careful at this point, be sure to find out whether the function is to return an object "copy" or only return "alias" on it, otherwise the program will be wrong.
The function return value uses "the reference passes" the situation not to be many, this kind of way generally only appears in the class assignment function, the goal is realizes the chain expression.
For example:

Class A
{
A & operate = (const a &other);//Assignment function
};
A, B, C; A, B, C is the object of a

= B = c;//Normal chain assignment
(a = b) = c;//abnormal chained assignment, but legal
the content of the return value is not allowed to be altered if the return value of the assignment function is modified with a const modifier. In the example above, statement a = B = c is still correct, but the statement (a = b) = c is illegal.

7. Const member function
any function that does not modify a data member (that is, a variable in a function) should be declared as a const type. If you accidentally modify a data member while writing a const member function, or call another non-const member function, the compiler will point out the error, which will undoubtedly improve the robustness of the program. In the following program, the member function GetCount of the class stack is used only for counting, and logically getcount should be a const function. The compiler will indicate an error in the GetCount function.

Class Stack
{public
:
void Push (int elem);
int Pop (void);
int GetCount (void) const; Const member function
private:
int m_num;
int m_data[100];
int Stack::getcount (void) const
{
+ + M_num;//Compile error, attempt to modify data member M_num
POP ();//Compile error, attempt to invoke non-const function
return m_num;
}

The declaration of a const member function looks strange: The const keyword can only be placed at the end of a function declaration, presumably because other places are already occupied.
Some rules about the const function:

The

A. Const object can access only the const member function, not the const object, which has access to any member functions, including const member functions. The members of the
B. Const object are not modifiable, but objects maintained by the const object through pointers can be modified. The
C. Const member function cannot modify the data of an object, regardless of whether the object has a const nature. It is checked at compile time, based on whether to modify the member data.
E. However, a data member with the mutable modifier, which can be modified by any means in any case, can be modified by the const member function at this time.

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.