[webkit-dev] On returning mutable pointers from const methods

Maciej Stachowiak mjs at apple.com
Sun Oct 28 06:16:07 PDT 2012

On Oct 26, 2012, at 7:21 PM, Rik Cabanier <cabanier at gmail.com> wrote:

> On Fri, Oct 26, 2012 at 9:06 AM, Peter Kasting <pkasting at google.com> wrote:
> On Fri, Oct 26, 2012 at 8:27 AM, Rik Cabanier <cabanier at gmail.com> wrote:
> It is valid for a const method to return you a new object ie a const factory object. 
> In that case, const-ness would not be desired.
> Not really.  The point of this thread is that such functions may not modify an object's state themselves, but they vend access that can be used by the caller to modify it.
> Consider for example:
> Child* Parent::getNewChild() const; 
> Assuming the Parent doesn't have a list of its children (questionable), we can implement this without mutable pointers.  But then a caller can do:
> Child* child = parent->getNewChild();
> child->parent->mutate();
> this would only be possible if that parent object is casting away a 'const' somewhere or accessing a global non-const object.
> Maybe there should be a rule that 'mutable' or 'const_cast' should not be allowed.

I don't think that would be a good rule. The approach we try to take to 'const' is logical constness - a method can be const if it has no observable side effect. mutable is extremely useful for state that is not precomputed, but that is worth caching. Filling a cache to give an answer faster next time doesn't logically alter the object's state, even though on a literal level it alters internal state. You shouldn't need a non-const reference to an object just to call a getter that happens to cache its result. The fact that there is a cache at all is a hidden implementation detail. So in cases like this, it's useful to use 'mutable'.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.webkit.org/pipermail/webkit-dev/attachments/20121028/98b8c932/attachment.html>

More information about the webkit-dev mailing list