class A{public:A():member_(){}
int hashGetter() const{state_ = 1;return member_;}int goodGetter() const{return member_;}int getter() const{//member_ = 2; // errorreturn member_;}int badGetter(){return member_;}private:mutable int state_;int member_;};
该测试
int main(){const A a1;a1.badGetter(); // doesn't worka1.goodGetter(); // worksa1.hashGetter(); // works
A a2;a2.badGetter(); // worksa2.goodGetter(); // worksa2.hashGetter(); // works}
struct s{void val1() const {// *this is const here. Hence this function cannot modify any member of *this}void val2() const & {// *this is const& here}void val3() const && {// The object calling this function should be const rvalue only.}void val4() && {// The object calling this function should be rvalue reference only.}
};
int main(){s a;a.val1(); //okaya.val2(); //okay// a.val3() not okay, a is not rvalue will be okay if called likestd::move(a).val3(); // okay, move makes it a rvalue}
class Fred {public:void inspect() const; // This member promises NOT to change *thisvoid mutate(); // This member function might change *this};void userCode(Fred& changeable, const Fred& unchangeable){changeable.inspect(); // Okay: doesn't change a changeable objectchangeable.mutate(); // Okay: changes a changeable objectunchangeable.inspect(); // Okay: doesn't change an unchangeable objectunchangeable.mutate(); // ERROR: attempt to change unchangeable object}