[003] Use const whenever possible

Source: Internet
Author: User

3. Try to use const
Classic interview questions:

① State at least three functions of const
② Const char * P = X;
Char * const P = X;
The role of the two const above.

Speaking of this, it is best to talk about the const semantics:

1. Const Semantics
1). Replace # define
2) Make an object (variable), value, pointer, reference cannot be modified
3) Enable static objects of the class to be initialized within the class.
When we want to define a constant within the class, we may use const to modify it. Otherwise, initialization cannot be performed.

1 class print {2 Private: 3 static const int COUNT = 10; // cannot be written as static int COUNT = 10; here the type can only be integer 4 string info [count]; 5}; 6 const int print: count; (Appendix 1)

4) modify the function parameters and return values. For member functions of the class, you can determine that the data members of the class cannot be modified.
① Difference between adding const at the end of the function body and above
② Making the function return a constant value can often reduce accidents caused by customer errors, without giving up security and efficiency.
For example:

1 const cgi_ChangeVolumeOperationListData& GetData() const {2 return *_pData;3 }

Note: If the const is a constant, the meaning before the asterisk is the same after it is written after the type, for example:
Void F1 (const func * P); // F1 gets a pointer pointing to a constant (func) object
Void F2 (func const * P );
5). Use const to modify the member functions of the overloaded class.
For details, refer to the 3rd points below.

Let's take a look at the meaning of all const in this function:
Const char * const Foo (char const * const Str) const
The first const indicates that the return type is const, that is, the return value of this function cannot be used as the left value.
The second const indicates that the pointer is non-mutable, but this can be omitted because the return type is already Const.
The third const represents the constant of STR, so its content cannot be changed. It can be written before the char.
The fourth const represents the constant of the STR pointer, that is, the pointer cannot point to another address.
The fifth const indicates the constant of the function (provided that it is a member function of the class). The data member of the class cannot be modified.

2. Relationship between STL iterator and const

The so-called STL is actually

STL: Standard Template Library, standard template library
STL provides a set of container, iterator, function object, and algorithm templates. A container is an array-like unit with the same storage value type;
An algorithm is a prescription for specific processing. An iterator can be used to traverse objects in a container. Similar to pointers that can traverse arrays, It is a generalized pointer.

2) the STL iterator is named Const.
STL iterators are molded by pointers, and act like a T * pointer. Therefore, the reputation iterator for const is the same as the reputation pointer.
The same means that the iterator cannot point to different things, but the value of the things it points to can be modified. To make it point to a value that cannot be repaired
Can be defined as const_iterator, for example:

1 STD: vector <int> VEC; 2... 3 const STD: vector <int>: iterator iter = Vec. begin (); // The role of ITER is like T * const4 * iter = 10; // at this time, ITER is const and cannot be changed to 5 6 STD: vector <int> :: const_iterator iter = Vec. begin (); 7 + + ITER; // At this time * ITER is const and cannot be changed

3. Const member functions
1) The purpose of implementing const and member functions is to confirm the role of the member function and the const object. The reasons are as follows:
① Make the class interface easier to understand
② Make "operate const object" Possible

2) In member functions, if they only have different constants, they can be overloaded, for example:

 1 class string { 2 public: 3 char& operator[](int position){ //★ 4 return data[position]; 5 } 6 const char& operator[](int position) const { 7 return data[position]; 8 } 9 private:10 char *data;11 };

Then we can use the following:
String S1 = "hello ";
Cout <S1 [0]; // call a non-const
Const string S2 = "world ";
Cout <S2 [0]; // call const
★The return type of non-const operator [] must be a char reference-Char itself will not work, because changing a "return value is fixed
The Return Value of the type function is definitely illegal. Even if it is legal, due to the mechanism of "returning objects through values (rather than references)" in C ++,
A copy of S. Data [0] will be modified, instead of S. Data [0 ].

3) What is the exact meaning of a member function as const?
Two main ideas:
① Const (bitwise constness) in the Data sense)
② Conceptual const (conceptual constness), also known as logical constness
Bitwise constness:
If and only when the member function does not modify any data member of the object (except for static data members), that is, it does not modify any bit of the object, this member function is const.
In fact, bitwise constness is the definition of const in C ++. The const member function is not allowed to modify any data member of its object.
However, there is no absolute distinction between things, just as light is both linear and can be understood as photon. There will always be special cases:
Many member functions that do not comply with the bitwise constness definition can also be tested using bitwise. In particular, a member function that modifies the data pointed to by the pointer, its behavior is
However, bitwise constness is violated, but if the object only contains this pointer, this function is also bitwise const and will pass during compilation. (Example)

Class string {public: // constructor that points data to the copy string (const char * value) of the data pointed to by a value );... operator char * () const {return data;} PRIVATE: char * data ;};

Const string S = "hello"; // declare a constant object
Char * nasty = s; // call operator char * () const to obtain the pointer
* Nasty = 'M'; // modify S. Data [0]
Cout <s; // output "Mello"
This leads to the introduction of logical constness: a const member function can modify some data (BITs) of its object, but only when the client does not notice it. Example:

Class string {public: // constructor that points data to the copy string (const char * value) of the data pointed to by a value: lengthisvalid (false ){...} size_t length () const; private: char * data; size_t datalength; // The final calculated String Length bool lengthisvalid; // whether the length is valid currently}; size_t string :: length () const {If (! Lengthisvalid) {datalength = strlen (data); // error! Lengthisvalid = true; // Error !} Return datalength ;}

Here, the implementation of the length method obviously cannot be accepted by the compiler. To complete the change, you can use the keyword mutable:
Mutable size_t datalength;
Mutable bool lengthisvalid;
In this way, these member variables can be changed even in the const member function.

Conclusion: There is no fixed concept about Const. It can be understood as bitwise constness. I have both sides and logical constness ..

4) how to change a const member?
Introduction: Why do I need to change the const member?
If a large const member is repeatedly referenced by a variety of const members, there will be a lot of code duplicates, and problems such as Compilation Time, maintenance, and code expansion will follow.
In the age when bitwise constness and logical constness cannot have both sides, although mutable provides a solution, it sometimes cannot be solved (such as mutable
To join the C ++ standard ).
Solution ①: Remove const through type conversion (not recommended)
Pass a const object to a function that obtains non-const parameters, and you know that the parameter will not be modified inside the function.
Const char * klingongreeting = "nuqneh"; // "nuqneh" that is, "hello"
Char * length = const_cast <char *> (klingongreeting );
Note: Only when the called function (such as strlen in this example) does not modify the data referred to by its parameters can it work properly.

Solution ②: implemented through the local variable pointer
In a member function of class C, the this pointer has the following declaration:
C * const this; // in a non-const member function
Const C * const this; // In the const member function
In this case (that is, the compiler does not support mutable), if you want to make the problematic string: length version pair const and
If non-const objects are valid, you only need to change the type of this from const C * const to C * Const. You cannot do this directly, but you can use
Initialize a local variable pointer to point to the same object referred to by this for indirect implementation. Then, you can use this local pointer to access
Members you want to modify:

Size_t string: length () const {// defines a this pointer string * const localthis = const_cast <string * const> (this) that does not point to a local version of the const object ); if (! Lengthisvalid) {localthis-> datalength = strlen (data); localthis-> lengthisvalid = true;} return datalength ;}

Summary:
1) declaring something as const can help the compiler diagnose incorrect usage. Const can be applied to objects, function parameters, function return types in any scope,
Member function ontology.
2) the compiler enforces bitwise constness, but you should use conceptual constness when writing a program ).
3) When const and non-const member functions have essentially equivalent implementations, calling the const version for non-const versions can avoid code conflicts.

Appendix 1:
※About const, static, and static const
Const is read-only, which is only used in the Declaration;
Static generally has two roles, specifying the scope and storage method. for local variables, static specifies the static storage method. The initial value of each call is the value of the previous call. After the call, the bucket is not released;
For global variables, if the scope is divided by files, the variables are only visible in the current file; for static functions, they are also visible in the current module.
Static const is a collection of the above two. It is both read-only and visible only in the current module.

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.