Const usage in C ++

Source: Internet
Author: User

 

A simple example

Int & B (int & n)

{

N ++;

Return n;

}

Int main ()

{

Int a = 10;

Int & B = B (a); // call B and pass the reference of.

// In B, n refers to,

// Return n; return;

// The reference of a is returned to B, and B is

// Operations on n and B will directly affect a because they are the same thing.

Cout <B <endl;

Cout <a <endl;

}

----------------------------------

For

Int A (int n)

{

Return n;

}

Here, if it is int c = A (a); in this way, n is not a, but a copy of A (copy value)

The returned value is a "copy" and nothing is referenced. It has no effect on the original.

 

 

In C ++, returning references is a relatively obscure concept. In the book, this is just a general introduction and has not been expanded. I think it is necessary to expand this.

(1) first, return references. The parameters in the function must contain parameters that exist in the reference or pointer mode and must be returned. For example:

Int & abc (int a, int B, int c, int & result)

{

Result = a + B + c;

Return result;

}

This form can also be rewritten:

Int & abc (int a, int B, int c, int * result)

{

* Result = a + B + c;

Return * result;

}

However, the following form is not acceptable:

Int & abc (int a, int B, int c)

{

Return a + B + c; [yin: it is a local variable, so no !]

}

(2) because the return value directly points to a variable whose life cycle has not ended, any operation on the function return value (or function result) itself is actually, is the operation of that variable, which is the meaning returned by introducing the const type.

When the const keyword is used, it means that the return value of the function cannot be modified immediately! The following code cannot be compiled. This is because the return value immediately performs the ++ operation (equivalent to the ++ operation on the variable z). For this function, is not allowed. If the const is removed and then compiled, the result is passed and the result of z = 7 is printed.

Include <iostream>

Include <cstdlib>

Const int & abc (int a, int B, int c, int & result)

{

Result = a + B + c;

Return result;

}

Int main (){

Int a = 1; int B = 2; int c = 3;

Int z;

Abc (a, B, c) ++;

Cout <"z =" <z <endl;

SYSTEM ("PAUSE ");

Return 0;

}

 

When you see the const keyword, C ++ programmers may first think of const constants. This is not a good conditioned reflection. If you only know that the constant is defined with const, it is equivalent to using gunpowder only to make firecrackers. The greater charm of const is that it can modify the parameters, return values, and even the definition bodies of functions.

Const is the abbreviation of constant, which means "constant. All things modified by const are protected by force, which can prevent unexpected changes and improve program robustness. Therefore, many C ++ programming book suggestions: "Use const whenever you need ".

 

1. Use const to modify function parameters

If a parameter is used for output, No matter what data type it is, or whether it uses "pointer transmission" or "reference transmission", it cannot be modified by const, otherwise, the output function is lost. Const can only modify the input parameters:

If the input parameter uses "pointer passing", adding const can prevent accidental changes to the pointer and play a protective role.

For example, the StringCopy function:

Void StringCopy (char * strDestination, const char * strSource );

StrSource is the input parameter and strDestination is the output parameter. After the const modifier is added to strSource, if the statements in the function body attempt to modify the content of strSource, the compiler will indicate an error.

If the input parameter uses "value transfer", because the function will automatically generate a temporary variable for copying this parameter, the input parameter does not need to be protected, so do not add const modification.

For example, do not write the void Func1 (int x) function as void Func1 (const int x ). Similarly, do not write the void Func2 (A a) function as void Func2 (const A ). A is the custom data type.

For parameters of non-Internal data types, functions declared like void Func (A a) are destined to have relatively low efficiency. Because A temporary object of type a is generated in the function body for copying 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 transfer" only uses the parameter alias and does not need to generate A temporary object. However, the void Func (A & a) function has one disadvantage:

"Reference transfer" may change parameter a, which is not expected. It is easy to solve this problem by adding the const modifier, so the function eventually becomes void Func (const A & ).

Similarly, should void Func (int x) be rewritten to void Func (const int & x) to improve efficiency? It is completely unnecessary because the internal data type parameters do not have a structure or structure process, and replication is also very fast. The efficiency of "value transfer" and "reference transfer" is almost the same.

The problem is so lingering that I had to summarize the usage of the "const &" modifier input parameter.

For non-Internal data type input parameters, the "value transfer" method should be changed to "const reference transfer" to improve efficiency. For example, change void Func (A a) to void Func (const A & ).

For internal data type input parameters, do not change the "value transfer" method to "const reference transfer ". Otherwise, the function can not improve the efficiency, but also reduce the comprehensibility of the function. For example, void Func (int x) should not be changed to void Func (const int & x ).

 

2. Use const to modify the return value of a function

If the const modifier is added to the return value of a function in the "pointer passing" mode, the content of the function return value (that is, the pointer) cannot be modified. The return value can only be assigned to the same type pointer with the const modifier. For example, Function

Const char * GetString (void );

The following statement causes a compilation error:

Char * str = GetString ();

Which of the following statements is true?

Const char * str = GetString ();

If the function return value adopts the "value transfer mode", because the function copies the return value to an external temporary storage unit, adding the const modifier has no value.

For example, do not write the int GetInt (void) function as const int GetInt (void ).

Similarly, do not write function A GetA (void) as const A GetA (void), where A is the custom data type.

If the returned value is not an internal data type, it is indeed highly efficient to rewrite function A GetA (void) to const A & GetA (void. At this time, you must be careful to find out whether the function is to return a copy of an object or only return an alias. Otherwise, the program will fail.

There are not many cases where function return values are passed by reference. This method is generally only used in class assignment functions to achieve chained expression.

For example:

Class

{

A & operate = (const A & other); // value assignment function

};

A a, B, c; // A, B, c is the object of

 

A = B = c; // normal chained assignment

(A = B) = c; // The chain assignment is invalid, but valid.

If you add const to the return value of the value assignment function, the content of the returned value cannot be modified. In the preceding example, statement a = B = c is still correct, but statement (a = B) = c is invalid.

 

3. const member functions

Any function that does not modify the data member (that is, the variable in the function) should be declared as the const type. If the const member function is accidentally modified or other non-const member functions are called, the compiler will point out an error, which will undoubtedly improve the robustness of the program. In the following program, the stack-like member function GetCount is only used for counting. Logically, GetCount should be the const function. The compiler will indicate errors 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; // compilation error. An attempt is made to modify the data member m_num.

Pop (); // compilation error in an attempt to call a non-const Function

Return m_num;

}

The const member function declaration looks strange: the const keyword can only be placed at the end of the function declaration, probably because it is occupied elsewhere.

Rules for Const functions:

 

A. the const object can only access the const member function, but not the const object can access any member function, including the const member function.

B. Members of the const object cannot be modified. However, objects maintained by the const object through pointers can be modified.

C. The const member function cannot modify the object data, regardless of whether the object has the const nature. during compilation, it checks whether the object modifies the member data.

E. However, the data member with the mutable modifier can be modified by any means in any situation. Naturally, the const member function can be modified at this time.

 

Author: weiqubo

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.