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

Geoffrey Garen ggaren at apple.com
Mon May 30 16:02:20 PDT 2011

OK, how about this style guideline:

Const member functions:

Do use const member functions in classes that are simple data holders, to help distinguish between references that can modify the data and references that can't.

Do not use const member functions in complex classes that do a lot more than hold one piece of data, since the distinction is weak. Do not use const member functions for DOM or render tree nodes.


On May 29, 2011, at 1:20 PM, Darin Adler wrote:

> 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