Same function with const and without - When and why?

后端 未结 7 1762
终归单人心
终归单人心 2020-12-01 11:44
T& f() { // some code ... }
const T& f() const { // some code ... }

I\'ve seen this a couple of times now (in the introductory book I\'ve b

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 12:41

    As it was mentioned before, you can use const and non-const versions of functions depending on the const-ness of the invoking object. The paradigm is very often used with operator[] for arrays. A way to avoid code duplication (taken from Scott Meyers' book Effective C++) is to const_cast the const function return in a non-const overload, such as:

    // returns the position of some internal char array in a class Foo
    const char& Foo::operator[](std::size_t position) const
    {
        return arr[position]; // getter 
    }
    
    // we now define the non-const in terms of the const version
    char& Foo::operator[](std::size_t position) 
    {
        return const_cast( // cast back to non-const
            static_cast(*this)[position] // calls const overload
        ); // getter/setter
    }
    

提交回复
热议问题