C ++ const Summary

Source: Internet
Author: User

[Link to this article]

Http://www.cnblogs.com/hellogiser/p/cplusplus-const-summay.html

Seeing the const keyword, C ++ programmers may first think of const constants, which 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 ).UseConstModify 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 you enter parametersUse"Pointer transfer", Then add constModification can prevent accidental changes to the pointer and play a protective role.For example, the StringCopy function:

C ++ Code
1   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 change strSourceThe compiler will point out the 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. However, for parameters of non-Internal data types, functions declared like void Func2 (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 &)Because"Reference transfer"You only need to borrow the alias of a parameter and do not need to generate a temporary object.

However, the void Func (A & a) function has a 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 becauseParameters of the internal data type do not have a structure or structure process, and replication is fast,"Value Transfer"And"Reference Transfer"Almost equivalent efficiency.

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 constModifier Return Value
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 assignedConstThe same type of pointer.

C ++ Code
1   Const char * GetString (void );

The following statement causes a compilation error:

C ++ Code
1   Char * str = GetString ();

Which of the following statements is true?

C ++ Code
1   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:

C ++ Code
1
2
3
4
5
6
7
  Class
{
A & operator = (const A & other );
};
A a, B, c; // a, B, c are objects of type
A = B = c; // normal chain assignment
(A = B) = c; // abnormal chain assignment, but legal

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). constMember 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.

C ++ Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  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; // ERROR! Try to modify m_num
Pop (); // ERROR! Try to call non-const member 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:

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.

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

The const member function cannot modify the data of an object, regardless of whether the object has the const nature. During compilation, it checks whether to modify the member data.

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.

[Link to this article]

Http://www.cnblogs.com/hellogiser/p/cplusplus-const-summay.html

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.