C ++ keyword mutable

Source: Internet
Author: User

Mutable keywords: member variables modified by mutable can be changed even in common functions.
Mutable can be used in the following scenarios. Think twice before use.

    • There is a constant member function, but for debugging purposes, you want to track the number of calls of a constant function. Note that if you are considering using the mutable variable, it will violate the constant semantics, so please think twice.

 
Class employee {public: employee (const STD: string & name): _ name (name), _ access_count (0) {} void set_name (const STD: string & name) {_ name = Name;} STD: String get_name () const {_ access_count ++; return _ name;} int get_access_count () const {return _ access_count;} PRIVATE: STD: String _ name; mutable int _ access_count ;}
    • A more complex example may sometimes require caching the results of a complex operation.
Class mathobject {public: mathobject (): pi_cached (false) {} double Pi () const {If (! Pi_cached) {/* This is an insanely slow way to calculate pi. */PI = 4; for (long step = 3; Step <1000000000; Step + = 4) {PI + = (-4.0/(double) Step) + (4.0/(double) Step + 2);} pi_cached = true;} return PI;} PRIVATE: mutable bool pi_cached; mutable double PI ;};

The pI value is calculated only when Pi () is accessed for the first time. After the PI value is calculated, it is saved and the value is fixed, in this way, you only need to execute an operation that requires a large amount of computing to get a fixed value, and the logic of this function is still a constant function.

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.