现在的位置: 首页 > 综合 > 正文

What is a “const member function”?

2019年05月13日 ⁄ 综合 ⁄ 共 1500字 ⁄ 字号 评论关闭

What is a "const member function"?

A member function that inspects (rather than mutates) its object.

A const member function is indicated by a const suffix just after themember function's parameter list. Member functions with a
const suffix arecalled "const member functions" or "inspectors." Member functions without aconst suffix are called "non-const member functions" or "mutators."

 class Fred {
 public:
   void inspect() const;   
// This member promises NOT to change *this
   void mutate();          
// This member function might change *this
 };
 
 void userCode(Fred& changeable, Fred const& unchangeable)
 {
   changeable.inspect();   
// OK: doesn't change a changeable object
   changeable.mutate();    
// OK: changes a changeable object
 
   unchangeable.inspect(); 
// OK: doesn't change an unchangeable object
   unchangeable.mutate();  
// ERROR: attempt to change unchangeable object
 }

The error in unchangeable.mutate() is caught at compile time. There isno runtime space or speed penalty for
const.

The trailing const on inspect() member function means that theabstract (client-visible) state of the object isn't going to change.This is slightly different from promising that the "raw bits" of the object'sstruct aren't
going to change. C++ compilers aren't allowed to take the"bitwise" interpretation unless they can solve the aliasing problem, whichnormally can't be solved (i.e., a non-const alias could exist which couldmodify the state of the object). Another (important)
insight from thisaliasing issue: pointing at an object with a pointer-to-const doesn't guaranteethat the object won't change; it promises only that the object won't changevia that pointer.

抱歉!评论已关闭.