[webkit-dev] Do we have a style preference about const member functions?

Darin Adler darin at apple.com
Sun May 29 13:20:18 PDT 2011

On May 28, 2011, at 5:15 PM, Geoffrey Garen wrote:

> This came up in https://bugs.webkit.org/show_bug.cgi?id=59604.
> My personal preference is against const member functions because they force many error-prone code changes: introducing a const forces the transitive closure of all potential callees to change their signatures recursively, and if you get this wrong in the case of a virtual function, you introduce a very subtle set of bugs.

I think we do currently overuse const. There are many objects that are not really data holders, and it does not seem all that helpful to distinguish a const member function on such an object.

> I don't see much upside to const member functions because they're just an unenforced convention: sub-object and "mutable" data members are still non-const inside a so-called const function, and you can always const_cast away so-called const-ness, as WebKit currently does in 483 places.

I don’t fully agree. Although const is not an airtight mechanism, it can be helpful to make clear which functions are intended to have side effects and which are not. It’s helped me notice programming mistakes in the past. I don’t think the presence of mutable invalidates the helpfulness of const. I also don’t think the total number of calls to const_cast in WebKit is a good metric of how well const is working as a design pattern. Many of those calls are required due to working with libraries outside of WebKit such as CoreFoundation.

I think we should stop using const member functions on classes where the distinction is weak and it’s not paying off. The classes that immediately come to mind are the DOM elements and render tree nodes. Having a const pointer to one node in a tree is not all that meaningful since the const-ness is immediately lost if you move to a neighbor.

    -- Darin

More information about the webkit-dev mailing list