Inherited const when you need to mutate

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


On Tuesday, July 10, 2012 10:13:57 H. S. Teoh wrote:
> On Tue, Jul 10, 2012 at 06:48:51PM +0200, Timon Gehr wrote:
> > On 07/10/2012 06:45 PM, H. S. Teoh wrote:
> > >Yeah, this is logical const. Unfortunately, D doesn't have logical
> > >const.
> > 
> > Then why on earth is druntime acting as if it does?
> 
> Y'know, this brings up an interesting question. Do methods like toString
> _need_ to be const? That is, _physical_ const? Or are we unconsciously
> conflating physical const with logical const here?
> 
> Yes, certain runtime operations need to be able to work with const
> methods, but I wonder if those required const methods really belong to a
> core set of more primitive operations that guarantee physical const, and
> perhaps shouldn't be conflated with logical operations like "convert
> this object to a string representation", which _may_ require caching,
> etc.?

For a member function to be called on a const object, that function must be 
const. Whether it's logical const or physical const is irrelevant as far as 
that goes. As such, opEquals, opCmp, toHash, and toString all need to be const 
on Object, or it will be impossible for const Objects to work properly. 
Ideally, we'd alsa have a way to make it possible to have objects which aren't 
const and can't be const use those functions (which given physical constness 
obviously requires a separate function - be it an overload or an entirely 
separate function), but without those functions being const, const objects 
don't work.

Of greater debate is whether opEquals, opCmp, toString, and toHash on structs 
need to be const. Aside from druntime functions wanting to be to take their 
arguments as const, I don't see really see that as being necessary (though 
Walter wanst to require that they all be @safe const pure nothrow regardless 
of whether they're classes or structs), and since druntime probably has to 
templatize the functions which would take const anyway (and it can use inout 
or templatize them anyway if it doesn't need to), I wouldn't expect that much 
in druntime would require const. It should work with it, but it shouldn't need 
it. So, I don't think that structs really need to have those functions be 
const.

Classes is where it's a big problem - because of inheritance.

- Jonathan M Davis


More information about the Digitalmars-d mailing list