Inherited const when you need to mutate

Jonathan M Davis jmdavisProg at gmx.com
Tue Jul 10 13:11:05 PDT 2012


On Tuesday, July 10, 2012 12:00:59 H. S. Teoh wrote:
> I think hidden somewhere in this is an unconscious conflation of
> physical const with logical const.

I completely disagree at least as far as classes go. opEquals, opCmp, 
toString, and toHash must be _physically_ const, because they must work with 
physically const objects. There is _no_ way around that, and whether the 
actual internals of those functions could conceivably mutate something if they 
were logically const is irrelevant. The fact that D's const is physical const 
and that we must be able to have const object _mandates_ that those functions 
be const. There is no other option. There is no conflating of physical 
constness and logical constness there. It's purely a matter of making those 
functions callable by const objects (which happen to be physically const, 
because D's const is physical const, but even if D's const were logical const, 
the situation wouldn't change; those functions would still need to be const to 
work with const objects - it would just be logical const rather than physical 
const).

We may be able to make it possible to use non-const objects with those 
functions as well via overloading or whatnot, but as far as classes go, it's 
an absolute requirement that those functions be const. And they also need to 
be @safe, pure, and nothrow, or classes in general are similarly screwed with 
regards to those attributes.

Structs is the _only_ place where having those functions being required to be 
const is arguably conflating logical const and physical const. That's not the 
case with classes at all.

- Jonathan M Davis


More information about the Digitalmars-d mailing list