C ++ const reference

Source: Internet
Author: User
Const repost Summary

The connection cannot be found. Sorry...

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 statement in the function body tries 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) function as void func2 (const ). A is the custom data type.

For parameters of non-Internal data types, functions declared like void func (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) 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 you add const 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 returned value can only be assigned to the same type pointer with 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
Nothing will not be modifiedData member (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.

Const's personal summary

Const has two points to emphasize:

Const modifier return values: Modify built-in types and modify custom classes in two cases

When modifying the built-in type, adding const is no different from without const, because the built-in type itself is a const, combined with code analysis:

const int Foo(){int a=19;return a;}

Analysis: return a; before returning a, a space will be opened on the stack controlled by the non-Foo () function to store the value of A. The value in this space is a constant, it is const, so you do not need to add it. That is, const modifies temporary variables. Because of this, the built-in type function returned cannot be used as the left value, for example, Foo () = 3; is incorrect, because we cannot change the value of the const variable.
However, when the following code is used:

class A{public:int c;};

 

int main(){ A b; b.c=10; test()=b; return 0;

This function runs normally. If you see no, the function is taken as the left value. However, if const a test () is not supported.

Therefore, const cannot be added when operators are overloaded. Otherwise, a statement (a = B) = C is not allowed.

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.