[webkit-dev] Do we have a style preference about const member functions?
Maciej Stachowiak
mjs at apple.com
Tue May 31 11:00:33 PDT 2011
On May 31, 2011, at 10:54 AM, Peter Kasting wrote:
> On Mon, May 30, 2011 at 11:32 PM, Maciej Stachowiak <mjs at apple.com> wrote:
> A linked list node or tree node could useful have const methods, which give only const pointers/references to other nodes. If there is a reason const references to DOM nodes or renew objects are not useful, it is not due to the object graph participation itself, in my opinion.
>
> Indeed.
>
> The rule of thumb I use is that a const member function should only return const-ref or pointer-to-const objects (whether as return values or outparams). This helps ensure that the method is logically const, not just physically const, by preventing callers from using const methods to gain handles they can use to modify supposedly-const objects.
>
> It so happens that objects in trees/graphs tend to have functions that return pointers to other objects much more frequently than do independent data holders. Thus Geoff's rule ends up approximating my rule, but is not equivalent.
>
> As to use of const in general, I would prefer to see more of it rather than less, _assuming it is used only for logical constness_. See Scott Meyers' "Effective C++", item 3, for rationale.
I agree that const should be used for "logical constness". The rule should not be merely "doesn't alter any data members of this object" but rather "does not alter observable state of this object or vend any type of pointer or reference by which observable state of this object could be altered".
This explains both why mutable data members are ok (they are meant for cache/memoization purposes, and do not alter observable state) and why const methods returning non-const pointers to other objects in a mutually referencing graph are not.
Regards,
Maciej
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.webkit.org/pipermail/webkit-dev/attachments/20110531/eb09c066/attachment.html>
More information about the webkit-dev
mailing list