Complaints from common member functions and mutable

Source: Internet
Author: User

In C ++ member functions, a member function is called a common member function, for example, int get () const;

It is recorded in the encyclopedia that a common member function can only read the values of data members in the same class, but cannot be modified.

So what if it is modified? Of course we get a compilation error ....

What if I have to modify it? Then, mutable appears.

The mutable keyword is used to modify the value of a constant function.

Examples of mutable:

 

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;}

 

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;};

 

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.