c++ const member function that returns a const pointer.. But what type of const is the returned pointer?

后端 未结 5 1172
名媛妹妹
名媛妹妹 2020-12-07 10:13

I apologize if this has been asked, but how do I create a member function in c++ that returns a pointer in the following scenerios: 1. The returned pointer is constant, but

5条回答
  •  一向
    一向 (楼主)
    2020-12-07 10:39

    I don't know what book you have read, but if you mark a method const it means that this will be of type const MyClass* instead of MyClass*, which in its turn means that you cannot change nonstatic data members that are not declared mutable, nor can you call any non-const methods on this.

    Now for the return value.

    1 . int * const func () const

    The function is constant, and the returned pointer is constant but the 'junk inside' can be modified. However, I see no point in returning a const pointer because the ultimate function call will be an rvalue, and rvalues of non-class type cannot be const, meaning that const will be ignored anyway

    2 . const int* func () const

    This is a useful thing. The "junk inside" cannot be modified

    3 . const int * const func() const

    semantically almost the same as 2, due to reasons in 1.

    HTH

提交回复
热议问题