c++ constant function declaration variants?

后端 未结 3 1569
灰色年华
灰色年华 2021-01-21 21:22

Are all of the below declarations the same? If so, what is the standard way to declare a constant function?

const SparseMatrix transpose();

SparseMatrix transpo         


        
3条回答
  •  迷失自我
    2021-01-21 21:47

    The const on the left of the function name means the object that is returned cannot be modified. The const on the right means the method is apart of a class and does not modify any of its data members. Unless or course any of its data members are declared with the mutable keyword, in which case modification thereof is permitted despite a const guard.

    The placement of the const keyword is unimportant when the return type of the function is of non-pointer type:

     T const f(); // same as const T f();
    

    However, note that the placement of the const keyword matters when using a pointer as the return type. For example:

    const T* f();
    

    This method returns a pointer to a const T. That is, what it points to is immutable. So you cannot do an assignment through a dereference of the returned pointer:

    T* x = f();
    
    *x = y; // error: assignment of read-only location '*(const T*)x'
    

    When const is placed on the immediate right of the return type (that is a pointer), it means the pointer is const and cannot be changed.

    T* const f();
    
    int main()
    {
        T* x const;
    
        x = f(); // error: assignment of read-only variable 'x'
    }
    

    Furthermore, if we have const on both sides of a pointer return type, and have const denoting "no modification of class members", then it's read as the following:

    const T* const f() const;
    

    A const member function named f that returns a const pointer to a const T

提交回复
热议问题