Can const member functions take non const pointers as return values?


Let’s start with a piece of code

class A
    int *x;

    int *f() const { return x; }

Member functionfReturn to private memberxI think it will modify the membersx, right?

fyesconstMember function, I should add it before the return typeconstIs that right?

constThe member function should guarantee that it cannot change any data members.

As far as I’m concerned, functionfThe class was not modifiedAData members ofx, but can be modifiedxSo my question is, is this a violationconstWhat should function guarantee?


constA member function can only return a function that points to a memberconstPointer or reference.

However, your example does not return a pointer to a member; it returns exactly a copy of the pointer member. stayconstThis is allowed in member functions, even if the pointer happens to point to another member.

This will not be allowed (note that it is now returning the reference):

int *&f() const { return x; }

But this can (go back)constReference:

int *const &f() const { return x; }

Recommended Today

Use of Android WebView (super detailed usage)

1.1 overview of WebView Android WebView is a special view on the Android platform. It can be used to display web pages. This WebView class can be used to display only one online web page in the app. Of course, it can also be used to develop browsers. The internal implementation of WebView uses WebKit […]