Const parameters in C + +, const variables, const pointers, const objects, and const member functions

Source: Internet
Author: User

Const is the abbreviation of constant, the meaning of "constant unchanged". The const-modified items are protected against accidental changes and can improve the robustness of the program. So many C + + programming books suggest: "Use const whenever you need".

1. Parameters with the const modifier function

If the parameter is used for output, no matter what data type it is, or whether it takes "pointer passing" or "reference passing", it cannot be const-decorated, otherwise the parameter will lose output function. Const can only modify input parameters:

If the input parameter is "pointer passing", then the const modifier prevents accidental changes to the pointer, which can be used as a protective function.

For example, the Stringcopy function:

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

Where strsource is the input parameter, strdestination is the output parameter. After adding a const modifier to strsource, the compiler will indicate an error if the statement in the function body attempts to alter the contents of the strsource.

If the input parameter takes "value pass", since the function will automatically generate a temporary variable for copying the parameter, the input parameter is not intended to be protected, so do not add a const modifier.

For example, do not write the function void Func1 (int x) as void Func1 (const int x). Similarly, do not write the function void Func2 (a a) as void Func2 (const a a). Where a is a user-defined data type.

For parameters of non-intrinsic data types, functions declared like void Func (a a) are doomed to be more efficient than the bottom. Because the body of a function will produce temporary objects of type A for copying parameter A, the construction, copying, and destruction of temporary objects will consume time.

For efficiency, you can change the function declaration to void Func (A &a), because "reference passing" borrows only the alias of the parameter and does not need to produce a temporary object. But there is one drawback to the function void Func (A & A):

"Reference passing" has the potential to change the parameter a, which we do not expect. It is easy to solve this problem, and the const modifier is possible, 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 improve efficiency? It is completely unnecessary, because the parameters of the internal data type do not have the process of construction, destruction, and replication is very fast, and the efficiency of "value passing" and "reference passing" is almost equal.

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

For input parameters of non-intrinsic data types, the "value passing" method 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).

For input parameters of an internal data type, do not change the "value passing" method to "Const reference pass". Otherwise, it can not achieve the purpose of improving efficiency, but also reduces the comprehensible function. For example, void func (int x) should not be changed to void func (const int &x).

2. The return value of the const modifier function
The contents of a function return value (that is, the pointer) cannot be modified if the return value of the function returned by the "pointer Pass" method is added to the const modifier, and The return value can only be assigned to a const-decorated pointer of the same type. such as functions
const char * GetString (void);
A compilation error will appear in the following statement:
Char *str = GetString ();
The correct usage is
const char *STR = GetString ();
If the function return value is in "value passing", the const modifier has no value because the function copies the return value into an external temporary storage unit.
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 internal data type, overwriting function a geta (void) to const A & Geta (void) can indeed improve efficiency. But be careful at this point, be sure to figure out whether the function is going to return a copy of an object or just return an alias, or the program will go wrong.
There are not many occasions when the return value of a function is used as a "reference pass", which is usually only present in the assignment function of the class, in order to realize the chain expression.

For example:

1 classA2 { 3A & operate = (ConstA & Other);//Assignment Function4 } ; 5 6A, B, C;//A, B, C is an object of a7 8A = B = C;//Normal chained assignment9 Ten(A = b) = C;//Abnormal chained assignment, but legal


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

3. Const member functions
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 inadvertently modify the data member when you write the const member function, or if you call other non-const member functions, the compiler will indicate the error, which will undoubtedly improve the robustness of the program. In the following program, the member function GetCount of a 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.

1 classStack2 { 3      Public:4     voidPush (intelem); 5     intPop (void); 6     intGetCount (void)Const;//Const member Functions7     Private:8     intM_num;9     intm_data[ -]; Ten } ;  One  A intStack::getcount (void)Const - {  -+ + M_num;//compilation error, attempting to modify data member M_num thePop ();//compile error, attempt to invoke non-const function -     returnM_num; -}

The declaration of the 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:
A. Const objects can access only const member functions, and non-const objects have access to arbitrary member functions, including const member functions.
B. The members of a const object are not modifiable, but objects maintained by a const object through pointers can be modified.
C. The const member function cannot modify the object's data, regardless of whether the object is of a const nature. It is checked at compile time, based on whether to modify member data.
E. However, a data member with the mutable modifier can be modified by any means in any case, and the const member function at this time can modify its

Const parameters in C + +, const variables, const pointers, const objects, and const member functions

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.