const成员函数和常对象

内容简介

成员函数后加 const 表示这个函数不会修改对象的可观察状态。常对象只能调用 const 成员函数。

const 成员函数

class Person {
public:
    int age() const
    {
        return age_;
    }
 
    void set_age(int age)
    {
        age_ = age;
    }
 
private:
    int age_ = 0;
};

age() const 中的 this 类型可以理解为:

const Person* const this

所以不能修改普通成员变量。

mutable

mutable 成员可以在 const 成员函数中修改,通常用于缓存、统计等不影响逻辑状态的内容。

class Person {
public:
    int cached_value() const
    {
        cache_ = 100;
        return cache_;
    }
 
private:
    mutable int cache_ = 0;
};

常对象

const Person p;
p.age();      // 正确
// p.set_age(18);  // 错误:常对象不能调用非 const 成员函数

常对象可以访问静态成员,因为静态成员不属于某个对象。

最佳代码实践

  • 不修改对象状态的成员函数都应加 const
  • getter 通常应为 const
  • mutable 要谨慎使用,避免破坏 const 语义。
  • 函数参数只读对象时传 const T&

错误用法

class Person {
public:
    int age()
    {
        return age_;
    }
 
private:
    int age_ = 0;
};
 
void print(const Person& p)
{
    // p.age();  // 错误:age 没有 const,常引用无法调用
}

注意事项

  • const 成员函数表达接口承诺,不只是为了通过编译。
  • constcppthis指针 强相关。
  • mutable 不是随便绕过 const 的工具。

学习路径