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

后端 未结 5 1184
名媛妹妹
名媛妹妹 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:33

    int *const func() const

    You cannot observe the const here except for a few cases

    • Taking the address of func.
    • In C++0x, directly calling func with the function-call syntax as a decltype operand, will yield int * const.

    This is because you return a pure pointer value, that is to say a pointer value not actually stored in a pointer variable. Such values are not const qualified because they cannot be changed anyway. You cannot say obj.func() = NULL; even if you take away the const. In both cases, the expression obj.func() has the type int* and is non-modifiable (someone will soon quote the Standard and come up with the term "rvalue").

    So in contexts you use the return value you won't be able to figure a difference. Just in cases you refer to the declaration or whole function itself you will notice the difference.

    const int* func() const

    This is what you usually would do if the body would be something like return &this->intmember;. It does not allow changing the int member by doing *obj.func() = 42;.

    const int * const func() const

    This is just the combination of the first two :)

提交回复
热议问题