简体   繁体   中英

Can I have a const member function that returns *this and works with non-constant objects?

If I understand correctly, a member function that is not supposed to modify the object should be declared as const to let the users know about the guarantee. Now, what happens when that member function returns the reference to *this ? For example:

class C{
public:
    C &f() const {return *this;}
};

Inside C::f() , this has the type const C* , so, the following will not compile:

int main() {
    C c; // non-constant object!
    c.f();
    return 0;
}

Of course, we could provide a non-const version of C::f() to work on non-constant objects:

class C{
public:
    const C &f() const;
    C &f();
};

However, I do not believe that this is what we want. Note that the non-constant version does not change the object, but this promise to the users is not expressed... Am I missing something?

EDIT: Let me just summarize the question for clarity: f() does not modify the object on which it is called, so declaring it as C &f(); without making it a const member is misleading. On the other hand, I do want to be able to call f() on non-const objects. How do I resolve this situation?


EDIT: It comes out from all the discussion that took place in the comments that the question was based on an incorrect understanding of what const ness of a function member implies. The correct understanding that I am taking away for myself is:

A member function that returns a non-const reference is intended to allow its users to change the object through the returned reference. Therefore, even though this function does not change the object by itself, there should be no inclination to declare it to be a const member!

Your problem is the original function definition:

C &f() const {return *this;}

here you return a non-const reference to the const object, which would allow changing the const object and would be dangerous, therefore it's forbidden.

If you were to write it as

const C &f() const {return *this;}

would be callable from both const and non-const objects and would always return a const reference.

Of course, we could provide a non-const version of C::f() to work on non-constant objects. However, I do not believe that this is what we want.

Probably that is exactly what you want. It's the only way to return a non-const reference when called on non-const objects and keep const correctness when calling it on const objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM