Const member functions

Source: Internet
Author: User

What does a const mean by a member function?

There are two popular concepts: physical constants and logical constants.

C ++ defines Constants by using the concept of physical constants. That is, the const member function cannot change any non-static member variables in the object. For example:

1 class ctextblock 2 {3 Public: 4 ...... 5 STD: size_t length () const; 6 7 private: 8 char * ptext; 9 STD: size_t textlength; 10 bool lengthisvalid; 11}; 12 13 STD :: size_t ctextblock: length () const14 {15 if (! Lengthisvalid) 16 {17 textlength = STD: strlen (ptext); // The const member cannot be assigned to textlength and lengthisvalid18 lengthisvalid = true; 19} 20 return textlength; 21}

If an error occurs in the code above, the const Member cannot assign a value to textlength and lengthisvalid. How can this problem be solved?

The solution is simple: Use a const-related swing field of C ++: mutable.

Mutable releases the physical constant constraints of non-static member variables:

1 class ctextblock 2 {3 Public: 4 ...... 5 STD: size_t length () const; 6 7 private: 8 char * ptext; 9 mutable STD: size_t textlength; // These member variables may always be changed, even in the const member function, 10 mutable bool lengthisvalid; 11}; 12 13 STD: size_t ctextblock: length () const14 {15 if (! Lengthisvalid) 16 {17 textlength = STD: strlen (ptext); // now we can do this 18 lengthisvalid = true; 19} 20 return textlength; 21}

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.