CONST modifier function Parameter const modifier function return value Const modifier member function

Source: Internet
Author: User

Seeing the const keyword, the first thing a C + + programmer might think of is a const constant. This is not a good reflex. If you only know to define constants with const, then it is equivalent to using gunpowder only to make firecrackers. The greater charm of Const is that it can modify the parameters of a function, the return value, or even the definition of a function.

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
If the return value of a function that is passed by pointer is given a const modifier, the contents of the function return value (that is, the pointer) cannot be modified, The return value can only be assigned to a const-decorated pointer of the same type. For example, the function
const char * GetString (void); The
following statement will have a compilation error:
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).
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 passed by reference, which is generally only present in the assignment function of the class, in order to realize the chain expression.

For example:
Class A
{
A & operate = (const A & other); Assignment function
} ;
A, B, C; A, B, C is an object of a

A = B = C; Normal chained assignment
(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 function
any not modified data members (that is, variables in functions) functions should be declared as const types. 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.
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 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.
A few 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. The
C. Const member function cannot modify the data of an object, 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, the data member with the mutable modifier can be modified in any way by any means, and the const member function at this time can modify it

Const modifier function parameter const modifier function return value const modifier member function

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.