The mutable keyword of Bill's second season of C ++ Learning

Source: Internet
Author: User

The mutable keyword of Bill's second season of C ++ Learning
0. Reasons for the article

I plan to systematically organize the basic knowledge while reading the book, so that everyone can conveniently read the book. The collected knowledge should be referenced in books as much as possible, which is more reliable than the materials obtained on the Internet.

I. Role

Mutable is used to solve the problem that data members of objects cannot be modified in common functions.

In some cases, if you want to modify the value of a member variable in a constant function, add mutable before the variable. When the majority of data members of a constant object are still "read-only", modifications can be made to individual members.

# Include
  
   
# Include
   
    
Using namespace std; class Student {string Name; // The default value is private int times_of_getname; public: Student (char * name): Name (name), times_of_getname (0) {} string get_name () {times_of_getname ++; return Name;} void PrintTimes () const {cout <
    
   
  

The above program will report an error because the constant object s (student entity whose information cannot be modified) calls the non-const function get_name (), but if you change get_name () to const, times_of_getname cannot be modified.

However, if it is changed:

mutable int times_of_getname;string get_name() const{}

You can.

Ii. Precautions

Note the following when using the keyword mutable:

(1) mutable is only used for non-static and non-constant data members of the class.

(2) the mutable keyword prompts the compiler that the variable can be modified by the const function of the class.

(3) In a class, variables modified with mutable can only be a minority, or are not used at all. A large amount of use represents defects in programming.

References

[1] Chen Gang. C ++ advanced tutorial [M]. Wuhan: Wuhan University Press, 2008.

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.