[webkit-dev] Do we have a style preference about const member functions?
Brent Fulgham
bfulgham at gmail.com
Tue May 31 22:00:16 PDT 2011
On May 31, 2011, at 8:44 PM, Maciej Stachowiak wrote:
> For example, the compiler does not tell you that the following implementation of Node::previousSibling() (currently in our code!) is totally wrong from the "logical const" perspective:
>
> Node* previousSibling() const { return m_previous; }
>
> The correct way to do const-correctness here would require more verbosity:
>
> const Node* previousSibling() const { return m_previous; }
> Node* previousSibling() { return m_previous; }
>
> And the first variant would be dead code if we don't ever actually use const node pointers.
>
> Given your views on const-correctness discipline, what do you think is the right way to handle this situation? Note that this pattern comes up for many core DOM methods and many render tree methods.
One possible (though ugly) way of allowing the compiler to do some of this work for you is to declare the m_previous member as a const pointer, and then manipulate it only in specific routines using the "const_cast" operator to allow it to mutate. But this is probably a case of the cure being worse than the disease.
If we had logic that iterated over the node siblings in read-only fashion, we would ideally do so through a const iterator. In addition to documenting that we don't intend to mutate the object, it would provide potentially useful information that compilers could use to make aliasing decisions and so forth. Perhaps we never iterate over DOM nodes without intending to mutate them; if so, I would agree that there is no benefit to maintaining the const variation.
However I do not think (as the Node example might imply) that the fact that the compiler cannot identify ALL categories of const error means that we are better off washing our hands of const correctness.
In fact, due to the viral nature of const-ness changes, leaving them in (and continuing to maintain them) is a good long term approach since the first time you want to work with a const Node object you will have to resurrect const variations of methods across the object hierarchy.
-Brent
More information about the webkit-dev
mailing list