C ++ const mining in the root Q & A Series

Source: Internet
Author: User

I. Role of const:

1. Modify the value specified by const

Ex1.1:

Const int a = 2;

// A = 3; error: assignment of read-only variable

Just like a macro in C language, a will be put into the symbol list, but a is an internal link (internal link refers to only visible in the current file ). When the address of a is not obtained, the system does not allocate memory to a. When the address of a is obtained, the address is allocated to a. However, changing the content pointed to by a cannot change the value of, because a has been compiled into a symbol. Changing the content referred to by memory a has no results.

Ex1.2:

[Cpp]
# Include <iostream>
Using namespace std;
Int main (){
Const int ci = 2;
Cout <"the addr of ci is:" <(& ci) <endl;
Int * p = const_cast <int *> (& ci );
Cout <"the addr of p is:" <p <endl;
* P = 5;
Cout <"the value of ci is:" <ci <endl;
Cout <"the value of p is:" <(* p) <endl;
Return 0;
}

Output result:

2. Modify the function return value and modify the function content.

Add const to the function return value to prevent value assignment. Add const limitation to member function to prevent modification of the object member data.

Ex1.3:

[Cpp]
# Include <iostream>
Using namespace std;
Class Test {
Public:
Test ();
~ Test ();
Test & GetTest (){
Return * this;
}
Const Test & GetConstTest (){
Return * this;
}
 
Const Test & operator = (const Test & other ){
This-> value _ = other. value _;
Return * this;
}
 
Int ChangeValue (int value) const {
// Value _ = value; error: value _ is read only
Return value _;
}
Private:
Int value _;
};
Int main (){
Test test;
Test. GetTest () = test;
// Test. GetConstTest () = test; // error can't assignment to return value
Return 0;
}
 
In the function member function GetConstTest (), the returned value belongs to the const attribute, so the value cannot be assigned. In ChangeValue, the member function is limited to a const member function. Therefore, the description of the member data value _ cannot be modified internally.

3. program readability

With the const limitation, we can clearly tell the compiler and programmers that this value cannot be modified. At the same time, define the function parameter as a const reference, which is the same as passing the value, preventing the program from passing the entire object.

4. Program Efficiency

During the transfer of function parameters, variables are copied and transferred by value. If they are of the built-in type, less memory is occupied. copying a value does not matter. However, custom classes are far from being imagined. During parameter transfer, if it is passed by value, the object will call its own constructor and copy the entire object content, this is very efficient for classes that occupy a large amount of memory. If it is defined as reference or pointer passing, copy the pointer value.

5. replacing some macro responsibilities

C language was favored by programmers from all walks of life when it was invented. A major reason is the Macros in C language. Macros can not only define global data symbols, but also be used to construct very subtle functions. It is very convenient to define common variables and common functions. There are also many problems at the same time, such as no type check, but mechanical replacement, such as the classic "Max macro function" errors. Let's look at the example below.

Ex1.4:

[Cpp]
# Include <iostream>
Using namespace std;
# Define PI 3.14
# Define Log (str) cout <str <endl
# Define Max (a, B) a> B? A: B
 
Int main (){
Int a = 12;
Int B = 5;
Int max = Max (a, B );
Log (PI );
Log (max );
Log ("hello, world ");
Return 0;
}

However, the const in C ++ can avoid some problems.

1. type check

2. Name Conflict because macro-Defined variables are externally linked

3. If an error occurs in the macro variable, the compiler only replaces the macro variable with the value. Therefore, when the corresponding value is displayed, it will be very strange that this value comes from there, but you can clearly know the variable for the const variable.

 

Ii. const usage

1. Define built-in Constants

It is easy to define constants. Initialization is required when defining the const variable. The initial value can be a constant or a variable.

Ex2.1:

2. Restrict pointers and references

The pointer address is the memory allocated to the variable when the program runs, so the const pointer does not need to be initialized. Because the positions of const are different, the corresponding limit value is also different. The common method is to check the position of const and variable.

[Cpp]
Int num = 2;
Int other = 3;
 
// Assignment
Const int * ptr1 = & num
Int const * ptr2 = & num
Int * const ptr3 = & num
Const int * const ptr4 = & num
 
// Change value
Ptr1 = & other;
Ptr2 = & other;
// Ptr3 = & other; // read only error
// Ptr4 = & other; // read only error
 
// * Ptr1 = other; // read only error
// * Ptr2 = other; // read only error
* Ptr3 = other;
// * Ptr4 = other; // read only error


3. Restrict objects

Key Points of using const in a restricted object:

1. According to the bit limit, the memory occupied by the object cannot be changed. You can change the member data by converting this pointer into a non-const pointer.

2. Logical restrictions: data member restrictions in objects can be changed when the value of const member function is set to mutable.

3. const member data must be initialized in the initialization list.

4. In the class, only char, int, long, float, and double values can be assigned when declared through static const.

Ex2.3

[Cpp]
# Include <iostream>
Using namespace std;
 
Const int MAX_FRIEND = 100;
Class Player {
Public:
Enum {
Boy = 1,
Girl = 0
};
Player (): user_id _ (0), user_sex _ (boy ){}
~ Player (){}
 
Player (const Player &);
Const Player & operator = (const Player &);
 
Void SetUserId (int user_id );
Int GetUserId () const;
 
Void SetGroupId (int group_id) const;
Int GetGroupId () const;
 
Void SetUserAge (int user_age) const;
Int GetUserAge () const;
 
Void SetUserName (const char * user_name );
Void PrintPlayerInfo () const;
 
Private:
Int user_id _;
Mutable int group_id _;
Int user_age _;
String user_name _;
Const char user_sex _;
Static const int friend_count _ = MAX_FRIEND;
};
 
Player: Player (const Player & player): user_sex _ (boy ){
 
}
 
Const Player & Player: operator = (const Player & other ){
 
}
 
Void Player: SetUserId (int user_id ){
User_id _ = user_id;
}
 
Int Player: GetUserId () const {
Return user_id _;
}
 
Void Player: SetUserAge (int user_age) const {
Const_cast <Player *> (this)-> user_age _ = user_age;
}
 
Int Player: GetUserAge () const {
Return user_age _;
}
Void Player: SetGroupId (int group_id) const {
Group_id _ = group_id;
}
 
Int Player: GetGroupId () const {
Return group_id _;
}
 
Void Player: SetUserName (const char * user_name ){
User_name _ = user_name;
}
 
Void Player: PrintPlayerInfo () const {
Cout <"user id: \ t" <user_id _ <endl;
Cout <"user name: \ t" <user_name _ <endl;
Cout <"user sex: \ t" <user_sex _ <endl;
Cout <"user age: \ t" <user_age _ <endl;
Cout <"user group: \ t" <group_id _ <endl;
}
Int main (){
Const Player player1;
// Player1.SetUserId (100001 );
Player1.GetUserId ();
 
Player player2;
 
Player2.SetUserId (100001 );
 
Player2.SetGroupId (100 );
 
Player2.SetUserAge (21 );
 
Player2.SetUserName ("Jack ");
 
Player2.PrintPlayerInfo ();
Return 0;
}

In Example 2.3, we can see that const objects can only read the memory value and cannot rewrite the memory value. For the const member function, member data group_id _ is a variable that can be changed logically. In the SetUserAge (int user_age) function, the member data can be changed by converting the this pointer.

The program shown in this article is compiled in the gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.1.00) environment. The full text is complete.

Refer:

C ++ programming ideology 1

Copyright tive c ++ 3

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.