C++函数使用2个const修饰的作用?

函数体前面加一个const修饰有何作用?

const int isSSL() const {
   return is_ssl_;
}

请问这里有两处const修饰,各自有和作用呢?
和直接使用这个函数有什么区别?

int isSSL() {
   return is_ssl_;
}
阅读 2.9k
2 个回答

UPDATED thanks to @fefe

后面的 const 修饰行为:这个方法不能修改类中成员(mutable 成员除外)。

前面的 const 修饰返回值:如果返回复杂类型,其成员不能被修改。
若返回值(不管是什么类型),这里的 const 是摆设。
若返回指针,必需也用一个 const 指针来接收。

class C {
private:
    int prop1;
    mutable int prop2;
    
public:
    void method1(int p1, int p2) const {
        // prop1 = p1;
        //       ^ 报错
        // assignment of member 'C::prop1' in read-only object
        prop2 = p2; // OK because of `mutable`.
    }
    
    const int* method2(int i) {
        return new int(i + 1);
    }
    const int method3(int i) {
    // Here `const` is useless.
        return i + 1;
    }
};

int main() {
    C c;
    const int *i1 = c.method2(1); // OK
    // int i1 = c.method2(1);
    //        ^ 报错
    // invalid conversion from 'const int*' to 'int*'
    int i2 = c.method3(1); i2 = 1919810; // OK
}

和直接使用这个函数有什么区别?安全上的区别。
良好的 const 使用可以避免一些不必要的错误(不小心修改了某成员),也为其他的维护者带来便利(阅读代码时一目了然)

前面的const是修饰返回值的类型的,这里来说确实没啥用。。后面的const修饰成员函数,const成员函数只能被具有const属性的对象调用。

推荐问题